2016-03-24 117 views
1

我有查詢:如果在一個查詢中第一個爲空,如何獲得SELECT的第二個結果?

SELECT 
     cl.id client_id, 
     c.provider_id provider_id, 
     c.mcc mcc, 
     c.mnc mnc, 
     c.cost cost, 
     c.active active_cost 
     FROM costs c 
     INNER JOIN clients cl 
     ON cl.pref_provider_id = c.provider_id 
     WHERE c.mcc = 405 AND c.mnc = 11 AND c.active = 1 AND cl.id = 2 

,如果這個紀錄將不會被適當的條件可以發現,之後我需要寫第二選擇,並嘗試通過該條件(WHERE c.mcc = 405和C獲取記錄。 mnc = 0 AND c.active = 1 AND cl.id = 2)在一個查詢中,當然是

可以幫我嗎?儘可能少的查詢它是理想的:)

http://sqlfiddle.com/

+1

仍在掙扎?如果您願意,可以考慮遵循以下簡單的兩步操作步驟:1.如果您尚未這樣做,請提供適當的DDL(和/或sqlfiddle),以便我們可以更輕鬆地複製問題。 2.如果您尚未這樣做,請提供與步驟1中提供的信息相符的所需結果集。 – Strawberry

+0

@Strawberry,thx,我試圖創建我的bd http://sqlfiddle.com/#!9/ 57ea8/1 – AxOn

回答

1

您可以使用NOT EXISTS(),以檢查是否存在與MNC = 11

SELECT 
     cl.id client_id, 
     c.provider_id provider_id, 
     c.mcc mcc, 
     c.mnc mnc, 
     c.cost cost, 
     c.active active_cost 
     FROM costs c 
     INNER JOIN clients cl 
     ON cl.pref_provider_id = c.provider_id 
     WHERE c.mcc = 405 AND c.active = 1 AND cl.id = 2 
     AND (c.mnc = 11 or 
      c = 0 and NOT EXISTS(select 1 from costs cc 
            where cc.mcc = 405 AND cc.active = 1 AND 
            and cc.mnc = 11 and cl.pref_provider_id = cc.provider_id)) 
+0

「'where子句'中的未知列'c'」 – AxOn

+0

s1.c.mnc = 0和NOT EXISTS(....)AS s1?也不能這樣工作 – AxOn

+0

@AxOn立即嘗試.. – sagi

0
SELECT 
cl.id client_id, 
c.provider_id provider_id, 
c.mcc mcc, 
c.mnc mnc, 
c.cost cost, 
c.active active_cost 
FROM (select * from costs LIMIT 100 OFFSET 1) c 
INNER JOIN clients cl 
ON cl.pref_provider_id = c.provider_id 
WHERE c.mcc = 405 AND c.mnc = 11 AND c.active = 1 AND cl.id = 2; 
0

記錄試試這個:

SELECT cl.id client_id, 
     case when c1.provider_id is not null then c1.provider_id else c2.provider_id end provider_id, 
     case when c1.mcc is not null then c1.mcc else c2.mcc end mcc, 
     case when c1.mnc is not null then c1.mnc else c2.mnc end mnc, 
     case when c1.cost is not null then c1.cost else c2.cost end cost, 
     case when c1.active is not null then c1.active else c2.active end active_cost 
FROM clients cl 
left outer join costs c1 ON cl.pref_provider_id = c1.provider_id and c1.mcc = 405 AND c1.mnc = 11 AND c1.active = 1 
left outer join costs c2 ON cl.pref_provider_id = c2.provider_id and c2.mcc = 405 AND c2.mnc = 0 AND c2.active = 1 
where AND cl.id = 2 
and (c1.provider_id is not null or c2.provider_id is not null) 
相關問題