我知道此主题已经在此处讨论过,但我需要对其他问题有不同的结果。
我需要在机构名称和候选人姓氏上订购一些结果。
SELECT DISTINCT candidates.*, histories.job_title, institutions.name
FROM candidates
JOIN histories ON histories.candidate_id = candidates.id
JOIN institutions ON histories.institution_id = institutions.id
WHERE candidates.id IN (1,3,4,6)
ORDER BY institutions.name, candidates.last_name;
我的问题是目前这将返回所有候选人加入历史(当前/过去的就业),但如果我添加
AND histories.finish_date IS NULL
不会返回没有历史记录或设置完成日期的候选人。
谢谢,Alex
子查询
SELECT DISTINCT candidates.*,
(SELECT institution_id
FROM histories
WHERE histories.candidate_id = candidates.id AND histories.finish_date IS NULL
LIMIT 1) AS job_title
FROM candidates
JOIN institutions ON histories.institution_id = institutions.id
WHERE candidates.id IN (1,3,4,6)
答案 0 :(得分:0)
尝试在历史记录表中使用左连接:
SELECT DISTINCT candidates.*, histories.job_title, institutions.name
FROM candidates
LEFT JOIN histories ON histories.candidate_id = candidates.id AND histories.finish_date IS NULL
JOIN institutions ON histories.institution_id = institutions.id
WHERE candidates.id IN (1,3,4,6)
ORDER BY institutions.name, candidates.last_name;
我无法验证这一点,你必须为我做。它应该归还所有候选人及其历史(如果有的话)。