即使没有使用LEFT JOIN的活跃工作,我也试图显示项目,但是它似乎不起作用。我怀疑这是一个明显的错误,请提供帮助:
SELECT
`projects`.`id` AS `project_id`,
`projects`.`name` AS `project_name`,
`jobs`.`id` AS `job_id`,
`jobs`.`title` AS `job_title`,
`jobs`.`description` AS `job_description`
FROM
`projects`
LEFT JOIN `jobs` ON `projects`.`id` = `jobs`.`project_id`
WHERE
`projects`.`company_id` = 29
AND `jobs`.`active` = 0
ORDER BY
`projects`.`name`,
`jobs`.`title` asc
SQLFiddle:http://sqlfiddle.com/#!9/305373/1
期望的结果将是包含没有匹配作业的项目列表(因此具有null
值)。
答案 0 :(得分:3)
您需要将where
上的jobs
条件移动到on
:
SELECT . . .
FROM `projects` LEFT JOIN
`jobs`
ON `projects`.`id` = `jobs`.`project_id` AND
`jobs`.`active` = 0
WHERE `projects`.`company_id` = 29
在jobs
上进行比较。active
将外部联接转换为内部联接,因为NULL
的值不匹配。
答案 1 :(得分:3)
将where
子句与ON
子句:
SELECT . . .
FROM `projects` LEFT JOIN
`jobs`
ON `projects`.`id` = `jobs`.`project_id` AND
`jobs`.`active` = 0
WHERE `projects`.`company_id` = 29;
答案 2 :(得分:2)
从加入条件中删除jobs.activve=0
SELECT
`projects`.`id` AS `project_id`,
`projects`.`name` AS `project_name`,
`jobs`.`id` AS `job_id`,
`jobs`.`title` AS `job_title`,
`jobs`.`description` AS `job_description`
FROM
`projects`
LEFT JOIN `jobs` ON `projects`.`id` = `jobs`.`project_id` and job.active=0
WHERE
`projects`.`company_id` = 29
ORDER BY
`projects`.`name`,
`jobs`.`title` asc
因为您的where条件使其成为内部联接