我基本上有两张桌子:
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
答案 0 :(得分: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 |
+------+------+-------+------------------------------------+
答案 1 :(得分:0)
SELECT a.id,a.name,a.info,GROUP_CONCAT(b.name 分离器'|' ) 来自AS a LEFT OUTER JOIN B as b ON b.id = a.id. GROUP BY a.id
返回
id name info group_concat(b.name SEPARATOR'|')
1个你好苹果|橙色|锤子
2 B世界玻璃杯
3 C Foo NULL