将两个表中的信息合并到一个表中

时间:2016-04-29 12:16:59

标签: mysql sql select

我需要将两个表中的信息组合到一个表中,下表是

table 1
+----+---------------+---------+
|id_k|   name        |  value  |
+----+---------------+---------+
| 1  | enak          | 4       |
| 2  | nor           | 3       |
+----+---------------+---------+

table 2
+------+------+---------+
| id_d | id_k |  feel   |
+------+------+---------+
|  1   |  1   | good    |
|  2   |  1   | better  |
|  3   |  1   | verygood|
+------+------+---------+

结果应该是

+------+------+-------+------------------------+
| id_d | name | value |            feel        |
+------+------+-------+------------------------+
|  1   | enak |   4   | good, better, verygood |
|  2   | nor  |   3   |                        |
+------+------+-------+------------------------+

这是我的代码[没有工作]

select k.name, k.value, s.feel
from table1 as k 
left join table2 as s on s.id_k=k.id_k

2 个答案:

答案 0 :(得分:1)

您可以使用gorup_concat函数将table2中的值连接到结果中的逗号分隔字符串:

SELECT   table1.id_k, name, value, GROUP_CONCAT(feel SEPARATOR ', ') AS feel
FROM     table1
JOIN     table2 ON table1.id_k = table2.id_k
GROUP BY table1.id_k

答案 1 :(得分:1)

http://sqlfiddle.com/#!9/3a7564/1

SELECT   t1.id_k, 
  t1.`name`,
  t1.`value`, 
  GROUP_CONCAT(t2.feel) AS feel
FROM     table1 t1
LEFT JOIN table2 t2
ON t1.id_k = t2.id_k
GROUP BY t1.id_k