2011-04-18 61 views
1

例如,我正在對同一個表進行內部連接。 我想從表1或表2中選擇那些值不爲null的字段。Mysql查詢:INNER JOIN和SELECT *表示任何表不爲空

這裏查詢爲例:

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有鎮域爲好,但我可以有null值。如果它不是空的,我需要選擇a2.town。 這與所有其他領域有關。 :)

可能嗎?

感謝;)

回答

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 JOINdiscounts是在查詢冗餘:在NULL記錄將永遠不會返回,因爲他們絕不會通過以下INNER JOIN匹配到ads a2

+0

是否有可能以動態的方式做到這一點?無需手動對每個字段進行操作? – Somebody 2011-04-18 10:42:37

+0

@Beck:我不明白這個問題。什麼意思是「手動做」? – Quassnoi 2011-04-18 10:49:54

+0

COALESCE(a2。*,a。*)我的意思是這種方式有可能嗎? :) – Somebody 2011-04-18 10:54:17

1

使用ANSI函數COALESCE,或MySQL的函數IFNULL。根據需要別名列

SELECT 
    a2.id, 
    a2.col2, 
    coalesce(a2.town, a.town) town, 
    IFNULL(a2.city, a.city) city, 
...etc