简体   繁体   English

如何从一个表中选择行作为CSV并根据键插入另一个表?

[英]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 . 我有两个表testatestb

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.idtestb.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.

相关问题 如何将数据插入表中,其中一个值应该是另一个表的外键? - How do I insert data into a table where one of the values should be a foreign key from another table? 如何从一个表中选择被MySQL中的另一个表过滤的行? - How do I select rows from one table filtered by another table in MySQL? 如何将一个表的主键值插入另一个表的外键列? - How do I insert primary key value from one table to foreign key column in another? 如何将数据插入一个表并获取主键作为外键插入另一个表中? - How do I insert data into one table & get the primary key to insert in another table as a foreign key? 如何根据一个表中的值选择另一个表中的行并对其排序? - How can I select and order rows from one table based on values contained in another? 如何将行从一个MySQL表复制到另一个表并基于变量更新值之一 - How do I copy rows from one MySQL table to another and update one of the values based on a variable MYSQL, SELECT 语法问题,我如何 select 表的行基于另一个表中的要求 - MYSQL, SELECT syntax problem, how do I select rows of a table based on a requirement in another table 我如何从 MySQL 表中的 select 行按一列分组,另一列具有所需值 - How do I select rows from a MySQL table grouped by one column with required values in another 如何根据在另一个表中的日期之后加时间戳的行从一个 mysql 表中选择行 - How can I select rows from one mysql table based on the row being timestamped after a date in another table 从一个表中选择多个列,然后作为行插入到另一个表中 - select multiple column from one table and insert into another as rows
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM