2015-09-25 123 views
1

我需要做一些select語句獲得簡單的數據(只有一行包含一個或幾個領域每個選擇)。幾個選擇單查詢 - 即使一個選擇返回空

簡單的例子:

select name, price from article where id=125 
select log, email from user where uid=241 

我想只能處理一個從PHP端單個語句(或:我不想做準備幾個語句,執行多個語句,捕獲並處理異常每次執行並最終獲取每個語句的結果...)。
我想:

select * from (
    (select name, price from article where id=125) as a, 
    (select log, email from user where uid=241) as b 
) 

如果每個子查詢返回的值偉大的工程:

name | price | log | email 
------------------------------------------ 
dummy | 12,04 | john | [email protected] 

,如果子查詢的一個返回空,整個select返回空
我想要的是:空結果子查詢的空值。
我嘗試了很多東西ifnull()coalesce(),但無法得到期待的結果(我知道如何使用它們的空值,但我沒有找到一種方法來處理它們在空結果集的情況下)。
我終於找到了左的解決方案加入:

select * from (
    (select 1) as thisWillNeverReturnEmpty 
    left join (select name, price from article where id=125) as a on 1 
    left join (select log, email from user where uid=241) as b on 1 
) 

它完美地工作,即使子查詢的一個返回空(或甚至兩者,因此「選擇1」)。
我在SO上找到的另一種方法是在每個子查詢中添加一個count(*)以確保有價值。

但它看起來很髒,我不能相信有沒有簡單的方法只是使用像ifnull()。 什麼是正確的做法?

+0

你有沒有用'UNION試圖選擇... UNION SELECT ...'? –

+0

謝謝。但是不同的查詢不需要具有相同的類型,也不需要相同數量的字段。我不太清楚,我怎麼知道哪一行屬於哪個查詢。 – fpierrat

回答

0

我終於找到了最好的辦法是:

select * from (
    (select count(*) as nbArt, name, price from article where id=125) as a, 
    (select count(*) as nbUser, log, email from user where uid=241) as b 
) 

這樣,沒有永遠的子查詢返回空,這解決了這個問題(總有至少一個「零」計數加空值)。當沒有物品被發現

樣品結果:

nbArt | name | price | nbUser | log | email 
---------------------------------------------------------------- 
    0 | null | null | 1  | john | [email protected]