让我们考虑两个表“学校”和“学生”。现在一个学生可能属于他生命中的不同学校,一所学校有很多学生。所以这是一个很多的例子。第三个表“链接”指定学生和学校之间的关系。
现在要查询我,我会执行以下操作:
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,...)等
答案 0 :(得分:4)
您可以使用GROUP_CONCAT
汇总功能:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat。
像这样:
Select st.uid, -- stands for student id
st.uname, -- stands for student name
GROUP_CONCAT sc.sname SEPARATOR ', ' as school_names,
-- 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
group by st.uid
答案 1 :(得分:1)
丑陋,但有效。
select st.uid
,st.uname
,group_concat(concat(sc.sid,'=',sc.sname)) as example1
,group_concat(sc.sid) as example2
,group_concat(sc.sname) as example3
from students st
left join links l on l.uid = st.uid
left join schools sc on sc.sid = l.sid
where st.uid = 3
group
by st.uid
,st.uname;