MySQL Left Join,如果为null,则从一个或另一个中选择一个字段

时间:2011-08-08 04:15:11

标签: mysql select null left-join

我正在尝试LEFT JOIN 2表。这很好。但我回来了两组名为setting_value的字段。我只是在tblSettingssetting_value为NULL时尝试获取tblAgencySettingssetting_value。我该怎么做呢?我知道我可以重命名字段,然后在PHP中我可以检查tblAgencySettingssetting_value如果为NULL则抓住tblSettingssetting_value但是我更喜欢保留它MySQL的。

SELECT `tblSettings`.`id`, `tblSettings`.`setting_name`,
       `tblSettings`.`setting_value`, `tblAgencySettings`.`setting_value`
FROM `tblSettings` LEFT JOIN `tblAgencySettings` 
ON `tblSettings`.`id` = `tblAgencySettings`.`setting_id`
AND `tblAgencySettings`.`agency_id` = '1'
WHERE `tblSettings`.`changeable` = '1'
我刚注意到的一个小问题。我没提到这个。如果tblAgencySettings.setting_value确实有值。但是更改不是1然后只需选择tblSettings.setting_value

2 个答案:

答案 0 :(得分:2)

只需添加COALESCE

SELECT `tblSettings`.`id`, `tblSettings`.`setting_name`,
       COALESCE(`tblAgencySettings`.`setting_value`, `tblSettings`.`setting_value`)
FROM `tblSettings` LEFT JOIN `tblAgencySettings` 
ON `tblSettings`.`id` = `tblAgencySettings`.`setting_id`
AND `tblAgencySettings`.`agency_id` = '1'
WHERE `tblSettings`.`changeable` = '1'

COALESCE函数返回你给它的第一个非NULL值,所以:

COALESCE(`tblAgencySettings`.`setting_value`, `tblSettings`.`setting_value`)

如果tblAgencySettings.setting_value不为NULL,则为tblSettings.setting_value;如果tblAgencySettings.setting_value为NULL,则为tblAgencySettings.setting_value

如果COALESCE( IF(`tblAgencySettings`.`setting_value` = 0, NULL, `tblAgencySettings`.`setting_value`), `tblSettings`.`setting_value` ) 也可以为零,并且您想忽略它以及NULL,那么您可以使用它而不是上面的COALESCE:

case
    when `tblAgencySettings`.`setting_value` = 0     then `tblSettings`.`setting_value`
    when `tblAgencySettings`.`setting_value` IS NULL then `tblSettings`.`setting_value`
    else `tblSettings`.`setting_value`
end    

如果第一个参数为真,则IF返回第二个参数,如果第一个参数为假,则返回第三个参数,因此上述使用将零转换为NULL。或者,您可以一直到CASE语句:

{{1}}

答案 1 :(得分:2)

将您的SQL语句更改为:

SELECT `tblSettings`.`id`, `tblSettings`.`setting_name`, 
   CASE WHEN `tblSettings`.`setting_value` IS NULL THEN `tblAgencySettings`.`setting_value` 
    ELSE `tblSettings`.`setting_value` END AS `setting_value` 
    FROM `tblSettings` LEFT JOIN `tblAgencySettings` 
    ON `tblSettings`.`id` = `tblAgencySettings`.`setting_id`
    AND `tblAgencySettings`.`agency_id` = '1'
    WHERE `tblSettings`.`changeable` = '1'

Here's a link to MYSQL CASE Statement for your reference.