在 postgresql 查询中检查布尔值真/假结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17812253/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:01:49  来源:igfitidea点击:

checking for boolean true / false result in postgresql query

sqlpostgresqllua

提问by mark li

I am running the following sql query in my web app:

我在我的 Web 应用程序中运行以下 sql 查询:

SELECT EXISTS (
SELECT id
FROM user
WHERE membership=1244)

i was expecting true(boolean data) as the result but I'm getting 't' or 'f' for false. How do I get it to return to my lua code a standard boolean?

我期待结果为(布尔数据),但我得到 't' 或 'f' 为假。如何让它返回到我的 lua 代码标准布尔值?

I found the following post:

我找到了以下帖子:

Reading boolean correctly from Postgres by PHP

通过 PHP 从 Postgres 正确读取布尔值

And so I tried to change my code to something like this:

所以我试着把我的代码改成这样:

SELECT EXISTS ::int (
SELECT id
FROM user
WHERE membership=1244)

or

或者

SELECT ::INT (SELECT EXISTS (
SELECT id
FROM user
WHERE membership=1244))

But I'm getting a syntax error.
Can you tell the best way to handle this? Should I be casting the resulting 't' to a boolean somehow? or is there a way to tell postgresql to return true / false instead of 't'/'f'?

但我收到语法错误。
你能说出处理这个问题的最佳方法吗?我应该以某种方式将结果“t”转换为布尔值吗?或者有没有办法告诉postgresql返回真/假而不是't'/'f'?

Thanks.

谢谢。

回答by Barbara Laird

You are so close

你是如此接近

SELECT EXISTS (SELECT id FROM user WHERE membership=1244)::int 

回答by slavoo

Try it with CASE

试试看 CASE

select       
  (case when exists (SELECT id FROM user WHERE membership = 1244)
    then 1 
    else 0 
  end) as column;

my test fiddle

我的测试小提琴

回答by Clodoaldo Neto

Your first query do indeed return a boolean. A tis shown as the returned value of the query

您的第一个查询确实返回一个布尔值。At显示为查询的返回值

select exists (select 1);
 exists 
--------
 t

But if you check its type it is a boolean:

但是如果你检查它的类型,它是一个布尔值:

select pg_typeof(exists (select 1));
 pg_typeof 
-----------
 boolean

You will have to check with the lua's postgresql driver manual how to properly handle it.

您必须查看 lua 的 postgresql 驱动程序手册如何正确处理它。

回答by Milen A. Radev

Your initial query is fine by itself:

您的初始查询本身很好:

SELECT id FROM user WHERE membership=1244

You just need to check if it returns a row or not.

您只需要检查它是否返回一行。