以下select语句返回零结果,为什么?
SELECT `post_job`.`id`,
`post_job_description`.`title`,
`employers_description`.`name`
FROM (`post_job`)
LEFT JOIN `post_job_description`
ON `post_job`.`id` = `post_job_description`.`post_job_id`
LEFT JOIN `employers_description`
ON `post_job`.`employers_id` = `employers_description`.`id`
WHERE `post_job`.`published` = 1
AND `post_job_description`.`language` IN ('en')
AND `employers_description`.`language` IN ('en')
AND `post_job`.`deleted` = 0
GROUP BY `post_job_description`.`post_job_id`
LIMIT 25
当我删除它时:
AND `employers_description`.`language` IN ('en')
它会返回数据,但employers_description
。name
的值不在英语
post_job表:
post_job_description表:
employer_description表:
答案 0 :(得分:1)
这个ON
条款:
`post_job`.`employers_id` = `employers_description`.`id`
用于将employers_description
表连接到post_job
表。
从post_job
表中选择单行(根据您发布的示例数据):
id employers_id published deleted
---------------------------------
1 2 1 0
根据上面提到的ON
子句,employers_description
提取了LEFT JOIN
中的以下唯一一行:
name id language
-----------------
MaIT ar 2 ar
因此,这个谓词:
`employers_description`.`language` IN ('en')
将此行过滤掉,但没有结果。如果你从WHERE
子句中取出这个谓词,那么你会返回这一行,但正如你从上面看到的那样language = ar
。
您必须将id
的{{1}}值从name = MaIT ar
更改为2
,以便{{>>语言版本来自{{} 1 {}由1
操作提取(如employers_description
表中的情况)。
作为旁注,或许您应该考虑通过在每个帖子中保留LEFT JOIN
并在单独的表中保留每个员工信息post_job_description
来规范化post_job_description
和employers_description
表。
答案 1 :(得分:1)
您与LEFT JOIN
加入的表格中的任何条件都必须放入ON
子句中。如果将其放在WHERE
子句中,则为没有匹配的行返回的空值将不符合此条件,并且它们会过滤掉整行。
此外,您的GROUP BY
列应来自主表,而不是LEFT JOIN
表中的一个。否则,所有具有空匹配的行将组合在一起。
所以将其改为
SELECT `post_job`.`id`,
`post_job_description`.`title`,
`employers_description`.`name`
FROM (`post_job`)
LEFT JOIN `post_job_description`
ON `post_job`.`id` = `post_job_description`.`post_job_id`
AND `post_job_description`.`language` IN ('en')
LEFT JOIN `employers_description`
ON `post_job`.`employers_id` = `employers_description`.`id`
AND `employers_description`.`language` IN ('en')
WHERE `post_job`.`published` = 1
AND `post_job`.`deleted` = 0
GROUP BY `post_job`.`post_job_id`
LIMIT 25