首页 > 编程知识 正文

mysql多表左连接查询,多个左连接查询sql语句

时间:2023-05-06 06:42:09 阅读:15656 作者:507

Say I have 2 tables,A and B,eachaentitycanpossiblyhavemultiplebentities,inonecaseifiwanttogetallb ' sofsomecertaina ' s,iging

select A.id aid,B.id bid from A

left join B on B.aid=A.id

where A.id=1

and it will return a result set like

aid bid

1 1

1 2

1 3

As you can see for the first column,all those1' sarekindaduplicates.isitpossibletomodifythesqlstatementtolethimreturnaresultltltike

aid bid

1,2,3

inotherwordstolinkallthebid ' stogetherasoneentity?

Also what if there's another table C,and each A can have multiple C's,howtoimakethesqlreturnaresultsetlike

aid bid cid

一,二,三十一,二

instead of

aid bid cid

1 1 1

1 2 1

1 3 1

1 1 2

1 2 2

1 3 2

Thank you very much

解决方案

What DBMS are you using?

I can't speak for others,but in MySQL,starting from 4.1,you can use GROUP_CONCAT

EG:

select A.id aid,group_concat(distinctb.id ) bid from A

left join B on B.aid=A.id

where A.id=1

GROUP BY a.id

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。