Jack The Baker
Jack The Baker

Reputation: 1893

mysqli UNION get data in correct column name

I want to get data from database with UNION , I defined link as newslink, and pic as articlepic but it show articlepic data under newslink column, how can I fix this?

SELECT * FROM
((SELECT date, link as newslink FROM news ORDER BY id DESC)
UNION
(SELECT date, pic as articlepic FROM article ORDER BY id DESC)) as x
ORDER BY date DESC LIMIT 6

Sample Data

I want to get articlepic data under articlepic column, and newslink under newslink column

Upvotes: 2

Views: 55

Answers (2)

Bhavin Solanki
Bhavin Solanki

Reputation: 1364

You are not able to get the different name of the column when using union in the query

SELECT * FROM
    (
        (
        SELECT
            DATE,
            link AS newslink,
            '-'  As articlepic         
        FROM news ORDER BY id DESC
    ) UNION (
    SELECT
        DATE,
        '-'  As newslink,         
        pic AS articlepic
    FROM article ORDER BY id DESC
)
    ) AS X
ORDER BY DATE DESC LIMIT 6

Upvotes: 0

ScaisEdge
ScaisEdge

Reputation: 133380

if you values in different column you must add null value in the select for not corresponding columns

SELECT * FROM
 ((SELECT date, link as newslink, null as articlepic 
  FROM news ORDER BY id DESC)
UNION
 (SELECT date, null, pic 
   FROM article ORDER BY id DESC)) as x
ORDER BY date DESC LIMIT 6

Upvotes: 7

Related Questions