如何在一行中显示所有唯一ID的多行数据

时间:2017-08-10 08:28:31

标签: mysql

我在下面查询选择不同来源的语言,但我想在一行中显示

    SELECT msg_id,
    CASE WHEN source=0 THEN language_name END AS 'language1',
    CASE WHEN source=2 THEN language_name END AS 'language2',
    CASE WHEN source=1 THEN language_name END AS 'language3'
    FROM languages 
     WHERE msg_id=90491


    msg_id  language1   language2   language3
    90491    Marathi     NULL        NULL
    90491    NULL        NULL        English
    90491    NULL        Hindi        NULL

但我希望结果为

   msg_id   language1   language2   language3
    90491    Marathi     Hindi       English

我如何得到它

1 个答案:

答案 0 :(得分:0)

您可以使用INNER个选择查询,例如:

SELECT l.msg_id,
 (SELECT language_name FROM languages WHERE msg_id = l.msg_id AND source = 0) AS 'language1',
 (SELECT language_name FROM languages WHERE msg_id = l.msg_id AND source = 1) AS 'language2',
 (SELECT language_name FROM languages WHERE msg_id = l.msg_id AND source = 2) AS 'language3'
FROM languages l
WHERE l.msg_id=90491

此查询假设表格中每个msg_idsource组合只有一条记录。