2011-01-07 179 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字符串