我有两张表testa
和testb
。
mysql> select * from testa;
+------+-------+
| id | dcac |
+------+-------+
| 1 | hello |
| 2 | world |
+------+-------+
2 rows in set (0.00 sec)
mysql> select * from testb;
+------+------+
| a_id | x |
+------+------+
| 1 | a |
| 1 | b |
| 1 | b |
| 1 | c |
| 2 | x |
+------+------+
5 rows in set (0.00 sec)
如何向[{1}}添加一列(x_list
),使其成为testa
的{{1}}的逗号分隔列表,只要x
为testb
testa.id
所以我期待的输出有点像这样 -
testb.a_id
我尝试使用一些复杂的+------+-------+--------+
| id | dcac | x-list |
+------+-------+--------+
| 1 | hello | a,b,b,c|
| 2 | world | x |
+------+-------+--------+
语句,然后我看了http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat(实际上并不太了解)
但我无法继续。我该怎么办? 感谢。
答案 0 :(得分:2)
尝试:
SELECT testa.id, testa.dcac, GROUP_CONCAT(testb.x)
FROM testb
INNER JOIN testa ON testb.a_id = testa.id
GROUP BY testb.a_id
您可以在此处查看结果:http://sqlfiddle.com/#!2/28887/2/0