美文网首页
mysql关于查询一对多数据展示的问题

mysql关于查询一对多数据展示的问题

作者: 一曲无忆 | 来源:发表于2019-11-08 14:59 被阅读0次

实例:用户表与用户联系人表与用户ID相关联,需要使用sql查询展示每个用户对应的联系人的一个情况

方案:使用GROUP_CONCAT()函数将多的那个表中的数据连接在一起

简化数据表
t_user : id, name
t_contact : id, user_id, mobile

示例1:

select tu.name, group_concat(tc.mobile) from t_user tu left join t_contact tc on tu.id = tc.user_id group by tu.id

示例2:

select tu.name, (select group_concat(tc.mobile) from t_contact tc where tu.id = tc.user_id) from t_user tu

相关文章

网友评论

      本文标题:mysql关于查询一对多数据展示的问题

      本文链接:https://www.haomeiwen.com/subject/rgaibctx.html