2011-01-11 175 views
15

whoMySQL的SELECT CASE WHEN東西然後返回空

wid--name-------father---mother 
1----Daisy------David----Liza 
2----Jenny------Joe------Judy 
3----Meggy------Mike-----Manuela 
4----Sarah------Joe------Judy 
5----Chelsea----Bill-----Hillary 
6----Cindy------David----Liza  
7----Kelly------Joe------Judy 

ages

aid---whoid---age 
1-----1--------0 
2-----2--------0 
3-----3-------14 
4-----4-------30 
5-----5-------22 
6-----6-------17 
7-----1-------18 

我希望該列表的結果:

id---name------age 
1----Meggy-----14 
2----Cindy-----17 
3----Daisy-----18 (Selected data that bigger than 0) 
4----Chelsea---22 
5----Sarah-----30 
6----Jenny-----30 (Her age is 0 on ages table and Sarah's age with same father and mother) 
7----Kelly-----30 (No data on ages table and Sarah's age with same father and mother) 

我試過查詢:

SELECT 
    *, 
    (CASE age 
     WHEN '0' THEN (
      SELECT age 
      FROM ages a 
      LEFT JOIN who w 
       ON w.wid = a.whoid 
      WHERE 
       w.father = father 
       AND 
       w.mother = mother 
      ORDER BY a.age DESC LIMIT 1 
     ) 
     ELSE age 
    END 
    ) AS newage 
FROM who 
LEFT JOIN ages 
    ON wid = whoid 
ORDER BY newage 

這是什麼問題?

回答

21

CASE … WHEN NULL永遠不會匹配任何東西,CASE NULL總會匹配ELSE條款(在你的情況下返回age,即NULL)。

使用此:

CASE COALESCE(age, 0) WHEN 0 THEN … ELSE age END 

更新:

您還需要別名的表,並在字段說明使用別名:

SELECT *, 
     CASE COALESCE(age, 0) 
     WHEN '0' THEN 
       (
       SELECT MAX(age) 
       FROM who wi 
       JOIN ages ai 
       ON  ai.whoid = wi.wid 
       WHERE wi.father = w.father 
         AND wi.mother = w.mother 
       ) 
     ELSE 
       age 
     END AS newage 
FROM who w 
LEFT JOIN 
     ages a 
ON  a.whoid = w.wid 
ORDER BY 
     newage 
+0

謝謝。這解決了訂購問題,但仍然有選擇正確的年齡問題。 – baturalpdincdari 2011-01-11 15:48:27

+0

@baturalpdincdari:別名表。 – Quassnoi 2011-01-11 15:49:52

0

的父親和母親在您的子查詢可能與您的外部查詢中的父親和母親混淆。還是你問爲什麼不是最優?