在案例表达式中分配子查询的值
我想获得一个值,如果它存在,如果它不存在,我想返回一个随机数(比这更复杂,但这就是它的本质)。
我认为我的查询看起来像这样:
SELECT
something,
CASE
WHEN EXISTS (SELECT column_1 FROM table_1 WHERE something)
THEN column_1
ELSE RANDOM()
END;
这显然是无效的。
我使用PostgreSQL,并且在PLPGSQL函数中。
我应该怎么办?
I want to get a value if it exists, if it doesn't exist I want to return a random number (it's a bit more complicated than that but that's the essence of it).
My query I think would look something like this:
SELECT
something,
CASE
WHEN EXISTS (SELECT column_1 FROM table_1 WHERE something)
THEN column_1
ELSE RANDOM()
END;
which is not valid obviously.
I use Postgresql and I am inside a plpgsql function.
What should I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我找到了!
使用 coalesce 我可以做到这一点
。 ,随机带头。
I found it!
using COALESCE I can do this:
When the first query does not return something, RANDOM takes the lead.
您不能从
存在
条件中引用该列,因为这仅会产生True或false。从子查询中的选定列也完全忽略了。因此,您需要在当时的零件中重复选择以获取列值:
注意当时分支中选择周围的括号。它们是标记为标量查询所必需的。您还需要确保
some_condition
仅返回一行You can't reference the column from an
EXISTS
condition as that only yields true or false. The SELECTed columns from the subquery are completely ignored as well.So you need to repeat the SELECT in the THEN part to get the column value:
Note the parentheses around the SELECT in the THEN branch. They are necessary to mark this as a scalar query. You also need to make sure that
some_condition
only returns a single row