【发布时间】:2011-01-07 17:59:30
【问题描述】:
让我们考虑两张表“学校”和“学生”。现在一个学生可能在他的生活中属于不同的学校,一个学校有很多学生。所以这是一个多对多的例子。第三个表“链接”指定学生和学校之间的关系。
现在要查询这个,我执行以下操作:
Select sc.sid , -- stands for school id
st.uid, -- stands for student id
sc.sname, -- stands for school name
st.uname, -- stands for student name
-- select more data about the student joining other tables for that
from students s
left join links l on l.uid=st.uid -- l.uid stands for the student id on the links table
left join schools sc on sc.sid=l.sid -- l.sid is the id of the school in the links table
where st.uid=3 -- 3 is an example
如果用户拥有多个学校,此查询将返回用户 id 的重复数据,因此我添加了group by st.uid 来解决此问题,但我还需要与同一用户相关的学校名称列表。有没有办法修复我写的查询而不是两个查询?例如,我想要 Luci 的学校(X、Y、Z、R、...)等
【问题讨论】:
-
我的解决方案是合并 Ronnis 和 Spiny Norman。我是这样做的 `GROUP_CONCAT((concat(sc.sid,'=',sc.sname) SEPARATOR ', ') as school_obj``
标签: mysql many-to-many