让我们考虑2个表格“学校”和“学生”。现在一个学生可能属于他一生中的不同学校,而一所学校有很多学生。所以这是一个很多例子。第三个表格“链接”指定了学生和学校之间的关系。多对多关系mysql select
我们查询这个我做了以下内容:
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
,但我还需要与同一用户相关的学校名称列表。有没有办法做到这一点,修复我写的查询,而不是有2个查询?举例来说,我希望学校的Luci(X,Y,Z,R,...)等
我的解决办法是既Ronnis的合并和CSV格式的字符串多刺诺曼。我这样做`GROUP_CONCAT((concat(sc.sid,'=',sc.sname)SEPARATOR',')as school_obj`` – Luci 2011-01-07 10:01:51