0

学生

student_id  FirstName   LastName
---------------------------------------------------
1           Joe         Bloggs
2           Alan        Day
3           David       Johnson

Student_Course

course_id   student_id  courseName
---------------------------------------------------             
1           1           Computer Science
2           1           David Beckham Studies
3           1           Geography   
1           3           Computer Science
3           3           Geography   

学生俱乐部

club_id student_id  club_name               club_count
---------------------------------------------------
1       1           Footbal                     10
2       1           Rugby                       10
3       1           Syncronized Swimming        10
4       3           Tennis                      15

在上面的示例中,id = 1 的学生参加了 3 门课程并且是 3 个俱乐部的成员。
如果我要找出学生参与的课程或学生所属的俱乐部,我可以做到,但我需要运行两个查询。是否可以对上面列出的表运行单个查询,以便结果如下所示:

输出

student_id      FirstName       Student_associated_courses          Student_associated_clubs 
---------------------------------------------------------------------------
1               Joe             1,2,3                               Football, Rugby, Syncronized swimming
3               David           1,3                                 Tennis

是否可以仅通过一个查询获得上述输出?我正在使用 JDBC 来获取数据,所以我想看看我是否可以避免多次旅行来获取必要的数据。

4

2 回答 2

2

GROUP_CONCATDISTINCTin一起使用MySQL

SELECT  a.student_ID, a.firstname,
        GROUP_CONCAT(DISTINCT b.course_ID),
        GROUP_CONCAT(DISTINCT  c.club_name)
FROM    student a
        INNER JOIN student_Course b
            ON a.student_id = b.student_ID
        INNER JOIN student_clubs c
            ON a.student_ID = c.student_ID
GROUP BY    a.student_ID, a.firstname
于 2012-11-01T13:35:52.083 回答
2

试试这样:

SELECT *
FROM Student s JOIN
(SELECT sc."student_id", listagg(sc."course_id", ',')within group(ORDER BY sc."course_id")
FROM Student_Course sc
GROUP BY sc."student_id") s_course ON s."student_id"=s_course."student_id"
JOIN (SELECT sl."student_id", listagg(sl."club_name", ',')within GROUP(ORDER BY sl."club_name")
     FROM Student_clubs sl
     GROUP BY sl."student_id") s_club ON s."student_id"=s_club."student_id"

“catch”是 LISTAGG 不适用于 DISTINCT 关键字

是一个小提琴

于 2012-11-01T14:55:50.217 回答