2015-09-12 194 views
1

我做級聯的SELECT:合併多個級聯選擇,優先

SELECT * FROM x WHERE a = 1 AND b = 2 AND c = 3 
=> If nothing found, try: SELECT * FROM x WHERE a = 1 AND b = 2 AND c = 0 
=> If nothing found, try: SELECT * FROM x WHERE a = 1 AND b = 0 AND c = 0 

至少其中一人有一個結果,但可以適用於所有情況的結果。我想合併這個邏輯並僅返回一個案例,即給定最多(!= 0)條件的案例。

謝謝!

回答

1

我可以回答使用UNION查詢和NOT EXISTS:

SELECT * FROM x WHERE a = 1 AND b = 2 AND c = 3 

UNION ALL 

SELECT * FROM x 
WHERE 
    a = 1 AND b = 2 AND c = 0 
    AND NOT EXISTS (SELECT * FROM x WHERE a = 1 AND b = 2 AND c = 3) 

UNION ALL 

SELECT * FROM x 
WHERE a = 1 AND b = 0 AND c = 0 
    AND NOT EXISTS (SELECT * FROM x WHERE a = 1 AND b = 2 AND c = 3) 
    AND NOT EXISTS (SELECT * FROM x WHERE a = 1 AND b = 2 AND c = 0) 

,但一個更聰明的解決辦法是這樣的:

SELECT * FROM x 
WHERE 
    (a, b, c) = (
     SELECT a, b, c 
     FROM x WHERE (a, b, c) IN ((1,2,3), (1,2,0), (1,0,0)) 
     ORDER BY (b=0) + (c=0) 
     LIMIT 1 
) 

我不知道這最後一個會獲得更好的性能。我會嘗試哪一個更好。

+0

我只是準備了這個小提琴:http://sqlfiddle.com/#!9/e4e7b2/1 – fthiella

+0

輝煌,謝謝! – root66