实例:
用户表t_user与用户联系人表t_user_contact通过用户ID相关联,需要使用sql查询展示每个用户对应的联系人的一个情况
数据表:
id | user_id | name | mobile |
---|
1 | 1 | 张三 | 8613020000000 |
2 | 2 | 李四 | 8615700000000 |
3 | 1 | 王五 | 8615000000000 |
4 | 2 | 马六 | 8618700000000 |
方案:
使用GROUP_CONCAT()函数将表中的多个数据连接在一起
SQL:
select tu.name, group_concat(tuc.mobile)
from t_user tu
left join t_user_contact tuc
on tu.id = tuc.user_id
group by tu.id
select tu.name, (select group_concat(tuc.mobile) from t_user_contact tuc where tu.id = tuc.user_id)
from t_user tu
结果:
姓名 | 联系人 |
---|
小明 | 8613020000000,8615000000000 |
小红 | 8615700000000,8618700000000 |