加入表时,Concat一对多

时间:2017-09-23 13:00:55

标签: mysql sql

我有这些表格:

主机:

+----+------+---------+-------------+------------+--------+-----------------------+-----------------------+-------+
| id | name |   url   | environment | instanceId | region |      created_at       |      updated_at       | value |
+----+------+---------+-------------+------------+--------+-----------------------+-----------------------+-------+
|  4 | test | testing | qa          |  foo       |  bar   | "2017-09-23 14:57:18" | "2017-09-23 14:57:18" |  1222 |
+----+------+---------+-------------+------------+--------+-----------------------+-----------------------+-------+

ddframes:

+----+-------+-------+
| id | value | owner |
+----+-------+-------+
|  1 |  1222 |     4 |
|  2 |   333 |     4 |
|  3 |   444 |     4 |
+----+-------+-------+
ddframe上的

owneridhosts的外键

我想要的输出是:

+----+------+---------+-------------+------------+--------+-----------------------+-----------------------+--------------+
| id | name |   url   | environment | instanceId | region |      created_at       |      updated_at       |   ddframes   |
+----+------+---------+-------------+------------+--------+-----------------------+-----------------------+--------------+
|  4 | test | testing | qa          | hiri       | sdf    | "2017-09-23 14:57:18" | "2017-09-23 14:57:18" | 1222,333,444 |
+----+------+---------+-------------+------------+--------+-----------------------+-----------------------+--------------+

将ddframe连接在一起。

我拥有的是:

SELECT h.*, d.value as ddframes
FROM hosts h
INNER JOIN ddframes d
ON h.id = d.owner
GROUP BY h.id;

但它产生类似于我想要的输出的东西,只是没有其他ddframes。只有第一个。

这可以实现吗?也许我的桌子'设计错了吗?

1 个答案:

答案 0 :(得分:4)

您需要group_concat()功能:

SELECT h.*, GROUP_CONCAT(d.value) as ddframes
FROM hosts h INNER JOIN
     ddframes d
     ON h.id = d.owner
GROUP BY h.id;

我应该注意。通常,在SELECT *查询中使用GROUP BY是个坏主意。假设hosts.id是唯一的(主键是),那么这是可以接受的。事实上,ANSI标准支持GROUP BY中唯一键的此构造。