2009-12-23 54 views
2

我基本上有兩個表:如何加入MySQL表?

A(id int, name varchar(10), info varchar(10)) 
B(id int, item varchar(10)) 

A 
1 A Hello 
2 B World 
3 C Foo 

B 
1 apple 
1 orange 
1 hammer 
2 glass 
2 cup 

注意C沒有任何項目。我想加入這兩個表得到這個:

1 A Hello apple|orange|hammer 
2 B World glass|cup 
3 C Foo null 

我熟悉的GROUP_CONCAT(item SEPARATOR '|')概念,但我不太知道如何編寫查詢,特別是獲得該行3 C Foo null

回答

4
mysql> SELECT a.id, a.name, a.info, group_concat(b.item SEPARATOR '|') 
     FROM a 
     LEFT OUTER JOIN b ON (a.id=b.id) 
     GROUP BY 1,2,3;                
+------+------+-------+------------------------------------+ 
| id | name | info | group_concat(b.item separator '|') | 
+------+------+-------+------------------------------------+ 
| 1 | A | Hello | apple|orange|hammer    | 
| 2 | B | World | glass|cup       | 
| 3 | C | Foo | NULL        | 
+------+------+-------+------------------------------------+ 

外連接解釋:http://en.wikipedia.org/wiki/Join_(SQL)#Outer_joins

+1

@Ed:LEFT OUTER JOIN是一樣的LEFT JOIN – Fortega 2009-12-23 13:57:23

+0

謝謝你,它的工作原理! – 2009-12-23 14:16:08

0

SELECT a.id,a.name,a.info,GROUP_CONCAT(b.name SEPARATOR '|') FROM A作爲 LEFT OUTER JOIN B爲B ON b.id = a.id GROUP BY a.id

回報

ID名稱信息GROUP_CONCAT(b.name SEPARATOR '|')
1。你好蘋果|橙色|錘
2 B世界玻璃|杯
的3C富NULL