我有两个简单的表,如下面的
users
id name surname
1 John Douglas
2 Sam Morris
3 Michael Johnatan
cells
id userId cellPhone
1 1 13809876543
2 1 13809876525
3 2 13809876450
结果,我想最后只使用Mysql:
result
name surname cellPhone
John Douglas 13809876543,13809876525
Sam Morris 13809876450
Michael Johnatan
这是我的SQL查询
SELECT
o.name,
o.surname,
CONCAT(ons.cellPhone, ',', ons2.cellPhone) as CellPhone
FROM
users as o
LEFT JOIN cells as ons
ON o.id = ons.userId
LEFT JOIN cells as ons2
ON o.id = ons2.userId AND
ons.id NOT LIKE ons2.id
GROUP BY o.id
所以,在这种情况下,最后我得到了这个结果:
result
Name Surname Phones
John Douglas 13809876543,13809876525
Sam Morris
Michael Johnatan
你可以看到,sql没有显示Sam的手机。据我所知,当用户有2个电话号码时会显示。我尝试了很多来解决它。如果有人帮忙,我会很感激..
答案 0 :(得分:2)
你可以这样做:
SELECT
users.name,
users.surname,
GROUP_CONCAT(cells.cellPhone) as CellPhone
FROM
users
LEFT JOIN cells
ON users.id = cells.userId
GROUP BY users.id
参考: