将子查询返回的行作为原始列的列

时间:2012-05-04 21:23:49

标签: mysql sql

我正在创建一个数据库,学生可以在这里注册研讨会,我有一个WorkshopRegistration表,用于保存StudentID和WorkshopID。我的目标是返回一个包含StudentName,SchoolName,Workshop1,Workshop2列的表。学生将永远不会参加2个以上的研讨会。我已经到了将一个研讨会作为一个专栏,但是我在第二个研讨会上遇到了麻烦。

SELECT Students.StudentID, Students.name, Schools.name, 
      (SELECT Workshops.title
       FROM Workshops
       WHERE Workshops.WorkshopID IN
              (SELECT WorkshopID
               FROM WorkshopRegistration
               WHERE WorkshopRegistration.StudentID=Students.StudentID)) as Workshop1,
      (SELECT Workshops.title
       FROM Workshops
       WHERE Workshops.WorkshopID IN
              (SELECT WorkshopID
               FROM WorkshopRegistration
               WHERE WorkshopRegistration.StudentID=Students.StudentID)) as Workshop2
FROM Students, Schools
WHERE Students.SchoolID=Schools.SchoolID;

2 个答案:

答案 0 :(得分:1)

我会略微更改您的查询,只要学生只能同时注册两个研讨会,这将有效:

使用正常工作的DEMO

查看此SQL Fiddle
SELECT t.StudentID
    , t.name as StudentName
    , s.name as SchoolName
    , ws1.Title as Workshop1
    , ws2.Title as Workshop2
FROM Students t
LEFT JOIN Schools s
    on t.SchoolID = s.SchoolID
LEFT JOIN 
(
    SELECT max(WorkshopID) as WorkshopID, StudentId
    FROM WorkshopRegistration 
    GROUP BY studentid
) w1
    ON t.StudentID = w1.StudentID
LEFT JOIN 
(
    SELECT min(WorkshopID) as WorkshopID, StudentId 
    FROM WorkshopRegistration 
    GROUP BY studentid
) w2
    ON t.StudentID = w2.StudentID
LEFT JOIN workshops ws1
    ON w1.workshopid = ws1.workshopid
LEFT JOIN workshops ws2
    ON w2.workshopid = ws2.workshopid
ORDER BY t.StudentID

结果:

enter image description here

答案 1 :(得分:1)

当学生只参加一个研讨会时,之前的解决方案将复制研讨会名称。我建议改为:

SELECT students.studentid, 
       students.name, 
       schools.name, 
       mintitle AS Workshop1, 
       ( CASE 
           WHEN mintitle = maxtitle THEN NULL 
           ELSE maxtitle 
         END )  AS Workshop2 
FROM   students 
       JOIN school 
         ON students.schoolid = schools.schoolid 
       JOIN (SELECT studentid, 
                    Min(title) AS minTitle, 
                    Max(title) AS maxTitle 
             FROM   workshop w 
                    JOIN workshopregistration wr 
                      ON w.workshopid = wr.workshopid 
             GROUP  BY studentid) w 
         ON w.studentid = stuents.studentid 

case语句处理只有一个研讨会的情况。请注意,通过将第二个连接更改为“LEFT OUTER JOIN”,即使没有研讨会,相同的查询也可以工作。处理两个以上的研讨会。 。 。好吧,这还需要另外一个问题。