MySQL连接两个表以生成具有逗号分隔值的列

时间:2017-08-29 07:39:24

标签: mysql inner-join

我有一个mysql问题,也许标题有点令人困惑,但这里有:

我有两张桌子

    TABLE A           TABLE B
+-----+--------+   +-----+--------+
| id  | NumCol |   | id  | NumCol |
+-----+--------+   +-----+--------+
| 101 |  123   |   | 101 |        |
| 101 |  124   |   +-----+--------+  
+-----+--------+   

现在我想在id上加入这两个,所以我得到这样的输出

+-----+--------+
| id  | NumCol |
+-----+--------+
| 101 | 123,124|
+-----+--------+

任何人都知道有一种方便的方法吗?

2 个答案:

答案 0 :(得分:3)

你有没有尝试过:

SELECT tableA.id, GROUP_CONCAT(tableA.NumCol) as NumCol
FROM tableA, tableB
WHERE tableA.id = tableB.id
GROUP BY tableA.id

答案 1 :(得分:2)

尝试此查询

SELECT tb.id,GROUP_CONCAT(ta.NumCol) AS NumCol FROM tableB AS tb
JOIN tableA AS ta ON ta.id=tb.id
GROUP BY tb.id