【问题标题】:many to many relationship mysql select多对多关系mysql选择
【发布时间】: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


【解决方案1】:

您可以使用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

【讨论】:

  • 听起来很有趣,我注意到您在错误的位置添加了 group by。应该在where之后。但是你的方法真的很有帮助。谢谢。
【解决方案2】:

丑陋,但有效。

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=Cambridge,2=Oxford,3=Haganässkolan)。
  • example_2 包含学校 ID 的 csv 字符串 (1,2,3)
  • example_3 包含学校名称的 csv 字符串(Cambridge、Oxford、Haganässkolan)

【讨论】:

  • 我喜欢这部分 concat(sc.sid,'=',sc.sname)
猜你喜欢
  • 1970-01-01
  • 2011-03-01
  • 2017-09-26
  • 2012-07-18
  • 1970-01-01
  • 2014-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多