2014-04-28 45 views
1

我試圖創建SQL查詢與CASE,如果字段不爲空我想從嵌套的SELECT中獲取值,否則我想我的選定的字段=' - '。如果該字段爲空,那麼它可以工作,但如果不是,那麼我會得到空值而不是嵌套查詢的結果。CASE MySQL的 - 選擇作爲價值

這是我的代碼:

SELECT 
    id, 
    CASE role 
     WHEN 0 THEN \'Handlowiec\' 
     WHEN 1 THEN \'Kierownik\' 
     WHEN 2 THEN \'Administrator\' 
    END AS role, 
    name, 
    email, 
    CASE manager 
     WHEN manager IS NULL THEN \'-\' 
     ELSE (SELECT name FROM User a WHERE id = manager) 
    END AS manager 
FROM User ' . $where . ' ORDER BY name 

我想經理或名「 - 」如果場「經理」爲空。

回答

1

這可以通過做一個連接,而不是嵌套查詢:

SELECT 
    u.id AS id 
    CASE u.role 
     WHEN 0 THEN \'Handlowiec\' 
     WHEN 1 THEN \'Kierownik\' 
     WHEN 2 THEN \'Administrator\' 
    END AS role, 
    u.name AS name, 
    u.email AS email, 
    COALESCE (m.name, '-') AS manager 
FROM User u 
LEFT OUTER JOIN User m ON u.manager = m.id ' . $where . ' ORDER BY name