2011-01-07 43 views
1

2つのテーブル "学校"と "学生"を考えてみましょう。現在、生徒は生徒の異なる学校に所属し、学校には多くの生徒がいます。これは多くの例から多くの例です。第3のテーブル「リンク」は、学生と学校との関係を指定する。これを照会する今多対多関係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

答えて

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

+0

ああ、そうだよ、今私はそれを編集しました、ありがとう:) –

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文字列が含まれている
+0

私はこの部分が好きですconcat(sc.sid、 '='、sc.sname ) – Luci