联合子查询中的MySQL外部查询引用不起作用

时间:2016-11-24 13:29:19

标签: mysql sql

任何人都可以帮我重建以下MySQL查询,以便它可以工作:

git fetch

该查询应该统计来自两个来源的所有不同学生,并按合同对其进行分组。

问题是对c.id的子查询引用。很明显,子查询对合同表一无所知。

我非常感谢帮助它发挥作用。

谢谢!

1 个答案:

答案 0 :(得分:1)

您需要在子查询中选择cs2.contract,然后在外部查询中将其与c.id连接。

SELECT c.id, COUNT(d.student_id) 
FROM contract c
JOIN (
    SELECT cs2.contract, student_id 
    FROM ilc_course ic
    JOIN contract_seat cs2 ON cs2.id = ic.contract_seat
    WHERE ic.valid = 1 AND cs2.valid = 1
        AND (ic.finished IS NULL OR ic.finished > CURRENT_TIMESTAMP)
    UNION
    SELECT cs2.contract, student_id 
    FROM glc_to_user_profile_student gtups
    JOIN glc_course gc ON gtups.glc_course = gc.id
    JOIN contract_seat cs2 ON gtups.contract_seat = cs2.id 
    WHERE gtups.valid = 1 AND gc.valid = 1 AND cs2.valid = 1
        AND (gtups.left_date IS NULL OR gtups.left_date > CURRENT_TIMESTAMP)
        AND (gc.end_date IS NULL OR gc.end_date > CURRENT_TIMESTAMP)
) d ON c.id = d.contract
GROUP BY c.id;

此外,由于UNION会从子查询中删除重复项,因此您无需在DISTINCT中使用COUNT()