Postgres - 在CASE WHEN中使用select语句

时间:2014-04-25 14:46:25

标签: postgresql

我执行条件时的情况选择语句&如果返回任何东西,那么我需要得到它的价值,但我收到错误

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语句之外获取该值?

1 个答案:

答案 0 :(得分:4)

尝试:

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