我正在尝试LEFT JOIN 2表。这很好。但我回来了两组名为setting_value
的字段。我只是在tblSettings
。setting_value
为NULL时尝试获取tblAgencySettings
。setting_value
。我该怎么做呢?我知道我可以重命名字段,然后在PHP中我可以检查tblAgencySettings
。setting_value
如果为NULL则抓住tblSettings
。setting_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
答案 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'