mysqli union以正确的列名获取数据

g6baxovj  于 2021-06-19  发布在  Mysql
关注(0)|答案(2)|浏览(347)

我想用union从数据库中获取数据,我将link定义为newslink,pic定义为articlepic,但它在newslink列下显示articlepic数据,如何解决这个问题?

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

样本数据
我想在articlepic列下获取articlepic数据,在newslink列下获取newslink数据

vc9ivgsu

vc9ivgsu1#

在查询中使用union时,无法获取列的其他名称

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
lymgl2op

lymgl2op2#

如果在不同的列中输入值,则必须在select中为不对应的列添加null值

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

相关问题