当条件我正在执行 select 语句并且如果返回任何内容时,我需要获取它的值,但我收到错误
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 语句之外获取该值?
尝试:
COALESCE((SELECT us.attr_value
FROM user_setting us
WHERE us.user_id = u.user_id),
(SELECT gs.attr_value
FROM global_user_setting gs
WHERE gus.attr_key='key'))
相反。问题的原因是,
us
别名的绑定在子选择之外不可见(因为它在“标量”上下文中使用)。整个子选择基本上是一个表达式,它将产生一个值。
另一种(恕我直言更好)方法是在
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 us ON us.user_id = u.user_id
WHERE u.user_id IN (1, 2, 3)
我在这里假设,这个连接最多会产生一行
user
的每行。