2

我正在创建一个数据库,学生可以在其中注册研讨会,并且我有一个保存 StudentID 和 WorkshopID 的表 WorkshopRegistration。我的目标是返回一个包含 StudentName、SchoolName、Workshop1、Workshop2 列的表。学生将永远不会参加超过 2 个研讨会。我已经到了将 1 个研讨会作为专栏的地步,但我在获得第二个研讨会时遇到了麻烦。

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;
4

2 回答 2

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 

案例陈述处理只有一个车间的情况。请注意,通过将第二个联接更改为“LEFT OUTER JOIN”,即使没有研讨会,相同的查询也可以工作。处理两个以上的车间。. . 好吧,那需要另一个问题。

于 2012-05-05T04:15:45.403 回答
1

我会稍微更改您的查询,只要学生只能同时注册两个研讨会,这将起作用:

使用有效的演示查看此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

结果:

在此处输入图像描述

于 2012-05-04T21:47:26.447 回答