2014-04-25 114 views
0

內部情況下,當條件我執行select語句&如果回報什麼,然後我需要得到它的價值,但我得到的錯誤Postgres的 - 使用select語句中CASE WHEN

ERROR: missing FROM-clause entry for table "us" 

查詢..

SELECT u.user_id, 
     CASE 
      WHEN 
        (SELECT us.attr_value 
        FROM user_setting us 
        WHERE us.user_id = u.user_id) IS NOT NULL THEN us.attr_value 
      ELSE 
        (SELECT gus.attr_value 
        FROM global_user_setting gus 
        WHERE gus.attr_key='key') 
     END 
FROM user u 
WHERE u.user_id IN (1, 
          2,3) 

錯誤出現在IS NOT NULL THEN us.attr_value我明白了這個問題,但找不到如何在select語句之外獲取該值?

回答

3

嘗試:

COALESCE((SELECT us.attr_value 
       FROM user_setting us 
       WHERE us.user_id = u.user_id), 
     (SELECT us.attr_value 
       FROM global_user_setting gs 
       WHERE gus.attr_key='key')) 

代替。問題的原因是es別名的綁定在子選擇之外是不可見的(因爲它在「標量」上下文中使用)。整個子選擇基本上是一個單一的表達式,它將產生一個單一的值。

另一個(恕我直言更好)的方法將是對enrollment_settings表左連接:

SELECT u.user_id, 
     COALESCE(us.attr_value, (SELECT gus.attr_value 
           FROM global_user_setting gs 
           WHERE gus.attr_key='key')) 
FROM user u LEFT JOIN user_settings es ON us.user_id = u.user_id 
WHERE u.user_id IN (1, 2, 3) 

我想在這裏,這將加入以每user行最單行屈服。