2014-01-24 105 views
1

我目前在MySQL查詢中單獨使用coallescing字段,但我想合併整個記錄。在MySQL中合併整個記錄

這可能嗎?

SELECT la.id, 
COALESCE((SELECT name FROM lookup_changed l0, 
      (SELECT MAX(id) id 
      FROM lookup_changed  
      WHERE lookup_id = 26 
      ) l1 
      WHERE l0.id = l1.id 
     ), la.name) name, 
COALESCE((SELECT msisdn FROM lookup_changed l0, 
      (SELECT MAX(id) id 
      FROM lookup_changed  
      WHERE lookup_id = 26 
      ) l1 
      WHERE l0.id = l1.id 
     ), la.msisdn) msisdn 
FROM lookup_added la 
WHERE la.id = 26 

@Alma執行 - 僞SQL是:

SELECT la.id, 
MULTICOALESCE((SELECT <name, msisdn> FROM lookup_changed l0, 
       (SELECT MAX(id) id 
        FROM lookup_changed  
        WHERE lookup_id = 26 
       ) l1 
       WHERE l0.id = l1.id 
      ), <la.name, la.msisdn>) <name, msisdn> 
FROM lookup_added la 
WHERE la.id = 26 
+0

我沒沒有意義。你能提供僞SQL嗎?(即它看起來應該如何) –

+0

@AlmaDo補充說,謝謝。 – fadedbee

回答

0

由於COALESCE()「迴歸[S]的第一個非空參數」,這聽起來像你想中檢索「第一個非從一組查詢「-NULL結果:

-- syntax error 
SELECT COALESCE(
    SELECT a FROM ta, 
    SELECT b FROM tb 
); 

-- roughly equates to 
(SELECT a AS val FROM ta WHERE a IS NOT NULL ORDER BY a LIMIT 1) 
UNION 
(SELECT b AS val FROM tb WHERE b IS NOT NULL ORDER BY b LIMIT 1) 
ORDER BY val LIMIT 1 ; 

評論:

  • 我加ORDER BY條款,否則「第一行」意味着什麼
  • LIMIT 1子句是可選的(但允許分結果早修整)
  • 周圍的子查詢中的括號是強制性