多行成一列

时间:2019-09-24 02:42:40

标签: mysql sql

table    A        B
column  key      name
         1       John
         1       Michael
         2       Alice
         2       Josh

在我执行此查询时,在数据库上:

SELECT A.key, GROUP_CONCAT(B.name SEPARATOR ', ') 
  FROM A 
  LEFT JOIN B ON A.key = B.key 
 WHERE B.name = 'John'
 GROUP BY A.key

我的输出

  key      name
  1        John

预期输出:

  key      name
  1        John, Michael

3 个答案:

答案 0 :(得分:1)

您可以在查询中添加HAVING子句,断言给定的key记录集包含名称John

SELECT
    a.`key`,
    GROUP_CONCAT(b.name) names
FROM A a
LEFT JOIN B b
    ON a.`key` = b.`key`
GROUP BY
    a.`key`
HAVING
    SUM(b.name = 'John') > 0;

注意:key是MySQL的保留关键字,您不应使用它来命名列(尽管也许您只是在上面给出了示例)。

答案 1 :(得分:1)

这是您的查询

select A.`key`, GROUP_CONCAT(B.'name' SEPARATOR ', ') 
from (select `key` from tblB where n='John' limit 1) as A 
inner join tblB B on B.`key` = A.`key`
group by A.`key`

答案 2 :(得分:1)

如果您需要包含名称John的结果,则可以使用以下带有exists关键字的查询:

SELECT A.key, GROUP_CONCAT(B.name ORDER BY B.name SEPARATOR ', ') as "Names"
  FROM A 
  LEFT JOIN B ON A.key = B.key 
 WHERE EXISTS ( SELECT 1 FROM B WHERE name = 'John' AND B.key = A.key )
 GROUP BY A.key;

Demo