例如我正在同一个表上进行内连接。 我想从表1或表2中选择那些值为空的字段。
以下是查询示例:
SELECT a2.*,a.town
FROM `ads` AS `a`
LEFT JOIN discounts d ON d.ad_id=a.id
INNER JOIN ads a2 ON a2.id=d.discount_ad_id
LEFT JOIN `departments` AS `dp` ON dp.department_id = a.department
LEFT JOIN `map_towns` AS `mt` ON mt.town_id = a.town
WHERE (a.department = 9 OR a.department = 15)
GROUP BY `d`.`discount_id`
a2也有城镇地区,但我可以拥有空值。我需要选择a2.town,如果它不是null,如果它是a.town。 这与所有其他字段有关。 :)
有可能吗?
谢谢;)
答案 0 :(得分:1)
使用ANSI函数COALESCE或MySQL函数IFNULL。根据需要对列进行别名
SELECT
a2.id,
a2.col2,
coalesce(a2.town, a.town) town,
IFNULL(a2.city, a.city) city,
...etc
答案 1 :(得分:0)
SELECT a2.*, COALESCE(a2.town, a.town)
FROM `ads` AS `a`
JOIN discounts d
ON d.ad_id = a.id
JOIN ads a2
ON a2.id = d.discount_ad_id
LEFT JOIN
`departments` AS `dp`
ON dp.department_id = a.department
LEFT JOIN
`map_towns` AS `mt`
ON mt.town_id = a.town
WHERE a.department IN (9, 15)
GROUP BY
`d`.`discount_id`
请注意,LEFT JOIN
上的discounts
在您的查询中是多余的:NULL
记录永远不会被返回,因为它们永远不会被以下INNER JOIN
到{{ 1}}。
答案 2 :(得分:0)
查看COALESCE
函数,返回第一个非null的参数。
SELECT COALESCE(a2.town, a.town)
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce