我有三张表,如出勤率,时间和地位。为了得到我的输出,我写了这个查询
SELECT * FROM status s
LEFT JOIN (
SELECT period_id,p_name,student_id,date,status
FROM period p
LEFT JOIN attendance a
ON p.period_id=a.period_id)t1
ON s.status=t1.status
但它没有提供所需的输出......任何人都可以提供帮助
出勤:
---------------------------------------------------------
id | student_id | period_id |date | Status |
--------------------------------------------------------
1 | 1 | 1 |2016-12-24 | Present
--------------------------------------------------------|
2 | 1 | 3 |2016-12-24 | Absent
--------------------------------------------------------|
3 | 2 | 1 |2016-12-24 | Late
--------------------------------------------------------|
4 | 2 | 2 |2016-12-24 | Present
期间:
-----------------------
period_id | p_name |
-----------------------
1 | period1 |
-----------------------
2 | period2 |
-----------------------
3 | period3 |
状态:
-------------------
id | status |
-------------------
1 | Present |
-------------------
2 | Absent |
-------------------
3 | Late
输出
-----------------------------------------------------
student_id | period_id | date | Status |
-----------------------------------------------------
1 | 1 | 2016-12-24 | Present |
-----------------------------------------------------
1 | 2 | 2016-12-24 | null |
-----------------------------------------------------
1 | 3 | 2016-12-24 | Absent |
-----------------------------------------------------
2 | 1 | 2016-12-24 | Late |
-----------------------------------------------------
2 | 2 | 2016-12-24 | Present |
-----------------------------------------------------
2 | 3 | 2016-12-24 | null
答案 0 :(得分:0)
LEFT JOIN
中的第一个表必须是包含结果中所需的所有行的表。在您的情况下,这应该是所有不同学生,日期和时期的完整交叉产品。所以查询应该是:
SELECT s.student_id, p.period_id, d.date, a.status
FROM (SELECT DISTINCT student_id FROM attendance) AS s
CROSS JOIN period AS p
CROSS JOIN (SELECT DISTINCT date FROM attendance) AS d
LEFT JOIN attendance AS a
ON a.student_id = s.student_id AND a.period_id = p.period_id AND a.date = d.date
ORDER BY d.date, s.student_id, p.period_id
似乎不需要status
表,因为您在attendance
表中冗余地具有状态名称,而不是status_id
。