使用MySQL我试图提取所有people
company_id
匹配3
的人person
,并比较favourites
表中是否存在job_id
。
我注意到,如果一个人没有people
,那么他们就不会通过以下查询输出。
以下查询输出1行,但在company_id
表中有3行与3
的{{1}}匹配
SELECT *,
j.company_id as companyid,
f.id IS NOT NULL AS jid,
p.id as pid,
f.id AS fave_id,
f.id IS NOT NULL AS fave
FROM people p
INNER JOIN job j
ON p.job_id = j.id
LEFT JOIN favourites f
ON f.people_id=p.id
AND f.user_id = 12
WHERE p.company_id = 3
ORDER BY p.id ASC
感谢任何帮助,让查询输出所有匹配的行,并检查favourites
表。
答案 0 :(得分:1)
如果你把左联接放在工作上,它会显示没有job_id的人。我更新了小提琴here。
SELECT
p.*,
j.company_id as companyid,
f.id IS NOT NULL AS jid,
p.id as pid,
f.id AS fave_id,
f.id IS NOT NULL AS fave
FROM people p
LEFT JOIN job j
ON j.id = p.job_id
LEFT JOIN favourites f
ON f.people_id=p.id
AND f.user_id = 12
WHERE p.company_id = 3
ORDER BY p.id ASC
答案 1 :(得分:1)
您应该将作业表的INNER JOIN更改为LEFT OUTER JOIN,以便无论它们是否存在于作业表中,都可以选择它们。