2011-01-07 3 views
1

2 개의 테이블 "학교"와 "학생"을 고려해 보겠습니다. 이제 학생은 평생 다른 학교에 소속 될 수 있으며 학교에는 많은 학생이 있습니다. 그래서 이것은 많은 예제에서부터 시작됩니다. 세 번째 테이블 "링크"는 학생과 학교 간의 관계를 나타냅니다. 이제 many to many relationship mysql select

내가 다음을 수행이를 조회하기 :이 쿼리는 그가 두 개 이상의 학교가있는 경우 사용자 ID의 중복 데이터를 반환합니다

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 

, 그래서 group by st.uid 추가이 문제를 해결하기 위해, 그러나 나는 또한 필요 같은 사용자와 관련된 학교 이름 목록. 2 개의 쿼리 대신에 작성한 쿼리를 수정하는 방법이 있습니까? 예를 들어 루시 (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