2017-01-17 180 views
2

我有一個表格式,像這樣:包含相同值的兩個不同領域結合的行

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 

??? < < - 不知道如何字 「標題=標題和源=源」

SOLUTION:我是缺少GROUP BY:

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

你需要一個合適的GROUP BY。 –

回答

2

用途:

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

啊...... GROUP BY,我覺得很傻。非常感謝 – Fish

1

試此

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

check on fiddle

相關問題