多个左连接的正确语法是什么,左表中的条件是什么?

时间:2015-06-26 15:57:34

标签: mysql join where

以下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_descriptionname的值不在英语

post_job表:

enter image description here

post_job_description表:

enter image description here

employer_description表:

enter image description here

2 个答案:

答案 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_descriptionemployers_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