讓我們考慮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,...)等
我的解決辦法是既Ronnis的合併和CSV格式的字符串多刺諾曼。我這樣做`GROUP_CONCAT((concat(sc.sid,'=',sc.sname)SEPARATOR',')as school_obj`` – Luci 2011-01-07 10:01:51