MySQL - 从同一个表中加入查询

时间:2015-01-10 04:36:23

标签: mysql join

期望的输出 - https://www.dropbox.com/s/1mnrabcefvezt89/test11.png?dl=0

我试图在同一个表中加入这4个不同的查询,但是我不知道怎么做。 最终输出为Attend_Date,P,A,MC(共4列)

SELECT Attendance.Attend_Date
FROM Student, Attendance
LEFT OUTER JOIN (
SELECT Attendance.Attend_Date, COUNT(Attendance.AttendDet_Type) as P
FROM Student, Attendance 
WHERE Student.Stud_ID = Attendance.Stud_ID 
AND Student.Stud_Class = '1A1' 
AND Attendance.Attend_Date BETWEEN '2014-01-01' AND '2014-12-01'  
AND Attendance.AttendDet_Type = 'P'
GROUP BY Attendance.Attend_Date
) ON Attendance.Attend_Date
WHERE Student.Stud_ID = Attendance.Stud_ID 
AND Student.Stud_Class = '1A1' 
AND Attendance.Attend_Date BETWEEN '2014-01-01' AND '2014-12-01'  
GROUP BY Attendance.Attend_Date

任何人都可以帮助我吗?非常感谢!!

2 个答案:

答案 0 :(得分:0)

尝试在from语句中添加两次相同的表,然后将它们设置为变量名并正确重命名所有内容。例如,

FROM Student S1, Attendance A1
WHERE S1.Stud_ID = A1.Stud_ID 

和另一个

FROM Student S2, Attendance A2
WHERE S2.Stud_ID = A2.Stud_ID 

问题是连接上的外部表和内部表存在冲突,可能导致您的问题

答案 1 :(得分:0)

好吧,伙计们。我设法得到了这个结果(https://www.dropbox.com/s/3l4q76mlskc8ze1/test12.PNG?dl=0)。如何加入来自同一列的另外两个查询,如此链接所示:https://www.dropbox.com/s/1mnrabcefvezt89/test11.png?dl=0

SELECT a1.Attend_Date, t.P
FROM Student s1, Attendance a1

RIGHT JOIN (
SELECT a2.Attend_Date, COUNT(a2.AttendDet_Type) as P
FROM Student s2, Attendance a2
WHERE s2.Stud_ID = a2.Stud_ID 
AND s2.Stud_Class = '1A1' 
AND a2.Attend_Date BETWEEN '2014-01-01' AND '2014-12-01'  
AND a2.AttendDet_Type = 'P'
GROUP BY a2.Attend_Date
) as t ON a1.Attend_Date = t.Attend_Date

WHERE s1.Stud_ID = a1.Stud_ID
AND s1.Stud_Class = '1A1' 
AND a1.Attend_Date BETWEEN '2014-01-01' AND '2014-12-01'  
GROUP BY a1.Attend_Date