簡體   English   中英

多對多關系mysql選擇

[英]many to many relationship 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等)

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

難看,但是行得通。

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包含一個csv的學校ID字符串(1,2,3)
  • example_3包含學校名稱的csv字符串(劍橋,牛津,哈甘斯卡科蘭)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM