postgresql 如果表中存在数字,则返回 1,否则返回 0
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27045322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return 1 if number exists in table and 0 otherwise
提问by thecoparyew
I want to return 1 if some number already exists in table and 0 otherwise.
如果表中已经存在某个数字,我想返回 1,否则返回 0。
I tried something but it doesn't work:
我尝试了一些东西,但它不起作用:
select
case when 100 in (select distinct id from test) then '1'
else '0'
from test
I want something similar to exists function that already exists in PostgreSQL, but instead of true
and false
I want 1
or 0
.
我想要类似于 PostgreSQL 中已经存在的exists函数的东西,但不是true
and false
I want 1
or 0
。
回答by Erwin Brandstetter
回答by Sam Choukri
If the field you are testing is the Primary Key (or some other unique constraint), then you can simply return the count (which will always be 0 or 1):
如果您正在测试的字段是主键(或其他一些唯一约束),那么您可以简单地返回计数(始终为 0 或 1):
SELECT count(*) FROM test WHERE id = 100;