2011-01-07 144 views
1

让我们考虑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,...)等

+0

我的解决办法是既Ronnis的合并和CSV格式的字符串多刺诺曼。我这样做`GROUP_CONCAT((concat(sc.sid,'=',sc.sname)SEPARATOR',')as school_obj`` – Luci 2011-01-07 10:01:51

回答

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 
+0

听起来有趣,我注意到你在错误的位置添加了组。应该是在哪里,但你的方法真的有帮助。谢谢。 – Luci 2011-01-07 09:59:05

+0

哦,呵呵,你是对的,我现在编辑它,谢谢:) – 2011-01-07 09:59:56

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; 
  • example_1给你值对,如(1 =剑桥,2 =牛津,3 =Haganässkolan)。
  • example_2包含学校IDS(1,2,3)
  • example_3包括学校名称(剑桥,牛津,Haganässkolan)的CSV字符串