[英]How do I select rows from one table as CSV and insert into another table based on a key?
I have two tables testa
and testb
. 我有两个表
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)
How do I add a column ( x_list
) to testa
such that it's the comma-seperated list of x
s from testb
wherever testa.id
is testb.a_id
我如何向
testa
添加一个列( x_list
),使得它是来自testb
的逗号分隔的x
s列表, testb
testa.id
是testb.a_id
So the output I'm expecting is somewhat like this - 所以我期待的输出有点像这样 -
+------+-------+--------+
| id | dcac | x-list |
+------+-------+--------+
| 1 | hello | a,b,b,c|
| 2 | world | x |
+------+-------+--------+
I tried using some complex join
statements and I looked at this http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat (did not really understand much) 我尝试使用一些复杂的
join
语句,我看了这个http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat (真的不太了解)
But I'm not able to proceed. 但我无法继续。 What do I do?
我该怎么办? Thanks.
谢谢。
Try: 尝试:
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
You can see result here: http://sqlfiddle.com/#!2/28887/2/0 你可以在这里看到结果: http : //sqlfiddle.com/#!2,28887 / 2/0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.