LEFT JOIN未显示空值

时间:2019-03-22 11:30:14

标签: mysql sql

即使没有使用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值)。

3 个答案:

答案 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条件使其成为内部联接