我正在加入不同的表,我希望它返回一个连接的值。作为一个基本示例,让我使用表格.people
和.contacts
。我想要发生的是直接查询(如果可能)使用.people
.contacts
的所有结果
为了详细说明,这是.people
的结构
+----+--------+
| id | name |
+----+--------+
| 1 | naaa |
| 2 | hey |
+----+--------+
这是 .contacts
+----+--------+--------+
| id | per_id | num |
+----+--------+--------+
| 1 | 1 | 1234 |
| 2 | 1 | 3456 |
| 3 | 1 | 8901 |
| 4 | 2 | 1111 |
+----+--------+--------+
我希望以某种方式返回
+----+--------+--------------------+
| id | name | num |
+----+--------+--------------------+
| 1 | naaa | 1234,3456,8901 |
| 2 | hey | 1111 |
+----+--------+--------------------+
是否可以使用MySQL Query?
答案 0 :(得分:1)
你可以使用`GROUP_CONCAT':
来实现它SELECT p.id, p.name, GROUP_CONCAT(num SEPARATOR ', ')
FROM people as p
INNER JOIN contacts as c on p.id = c.per_id
GROUP BY p.id
答案 1 :(得分:0)
检查这个。
SELECT p.id, p.name, GROUP_CONCAT(num SEPARATOR ', ') as num
FROM people as p
INNER JOIN contacts as c on p.id = c.per_id
GROUP BY p.id