我有桌子学生和相遇。我想将此WHERE转换为LEFT JOIN。这可能吗?
WHERE stu.student_id NOT IN (
SELECT student_id
FROM encounter
WHERE
AND deletion_date IS NULL
AND '2013-12-04'::date BETWEEN start_date AND Coalesce(end_date, '2013-12-04'::date)
)
答案 0 :(得分:3)
SELECT
...
FROM
student stu
LEFT JOIN encounter enc ON enc.student_id = stu.student_id
AND enc.deletion_date IS NULL
AND '2013-12-04'::date BETWEEN start_date AND COALESCE(end_date, '2013-12-04'::date)
WHERE
enc.student_id IS NULL
我个人会使用NOT EXISTS子查询
WHERE
NOT EXISTS (
SELECT 1
FROM encounter
WHERE student_id = stu.student_id
AND deletion_date IS NULL
AND '2013-12-04'::date > start_date
AND (end_date IS NULL OR '2013-12-04'::date < end_date)
)
以及与(student_id, start_date, end_date, deletion_date)
相遇的索引。
这样,子查询将相当于每个student
记录的一个索引查找操作,这应该相当快。如果它比替代品快,你必须自己做基准。
答案 1 :(得分:0)
这可以帮到你:
SELECT <columns you want to view> FROM student s
LEFT JOIN encounter e ON s.student_id != e.student_id
WHERE <provide your filtration here>