2016-11-26 97 views
0

我想在單個查詢中實現的是返回匹配特定條件的記錄的id,如果沒有找到,則返回另一個條件。所以這兩個標準有不同的優先級,一個簡單的'or'不會。SQL查詢返回具有不同優先級的兩個查詢的結果

我想出了兩種解決方案,但不知道這是否可以簡化:

select id,1 as n from <tablename> where <criterion1> 
    union select id,2 as n from <tablename> where <criterion2> 
    order by n asc limit 1; 

或:

select coalesce ((select id from <tablename> where <criterion1>), 
       (select id from <tablename> where <criterion2>)); 

我寧願什麼是不是有重複兩者的共同度查詢(實際上我選擇了更多列,因此必須並行維護這些列),並且這兩個查詢都涉及同一個表。

如果有快捷方式,我很樂意瞭解它。

回答

0

如果你想一排,用order bylimit

select t.* 
from t 
where <criterion1> or <criterion2> 
order by (case when <criterion1> then 1 else 2 end) 
limit 1; 
+0

好吧,這是我不需要重複瓦爾的優勢,但我必須爲標準這樣做。似乎我必須做一個或另一個。 – user52366