组合包含两个具有相同值的单独字段的行

时间:2017-01-17 22:31:49

标签: mysql

我有一个格式如下的表:

title            source              subject   
Bill hits Fred   newspaper 1/1/17    Bill     
Bill hits Fred   newspaper 1/1/17    Fred
Bill hits Fred   newspaper 1/1/17    Violence
Mary likes pie   newspaper 1/4/17    Mary
Mary likes pie   newspaper 1/4/17    Pie 
Mary likes pie   newspaper 1/4/17    Apple
John dies        newspaper 1/4/17    John 
John dies        newspaper 1/4/17    Obituary
...

我需要实现的是一个查询,它查找标题和源字段具有相同值的所有行,并组合成一个连接主题字段的记录。即上述数据的输出为:

title            source              subject   
Bill hits Fred   newspaper 1/1/17    Bill, Fred, Violence     
Mary likes pie   newspaper 1/4/17    Mary, Pie, Apple
John dies        newspaper 1/4/17    John, Obituary
...

我想我需要GROUP_CONCAT但不确定比较所有行的标题和源的确切语法。有点像:

select title, source, GROUP_CONCAT(subject) from mytable
WHERE

??? << - 不确定如何说出“title = title and source = source”

解决方案:我缺少GROUP BY:

SELECT title, source, GROUP_CONCAT(subject) from mytable GROUP BY title, source

2 个答案:

答案 0 :(得分:2)

使用:

SELECT title, source, GROUP_CONCAT(subject) from mytable GROUP BY title, source

答案 1 :(得分:1)

试试这个

select title,source,group_concat(subject) as subject from tbl5 group by title;

check on fiddle