对于PostgreSQL中的布尔数据类型,输出"是/否"而不是"t/f"

Ser*_*off 4 sql postgresql boolean

如何进行返回yes/no而不是t/f(true/false)的查询?

目前的解决方案是

SELECT credit_card_holders.token IS NOT NULL AS premium
Run Code Online (Sandbox Code Playgroud)

我发现了一个Ruby解决方案: Rails(或Ruby):Yes/No而不是True/False

但如果可能的话,宁愿在PostgreSQL中这样做.

Viv*_* S. 7

通过创建自定义类型,您也可以实现这一点,请参阅以下示例

create table foo (id int,xid int);
insert into foo values (1,2),(2,3);
Run Code Online (Sandbox Code Playgroud)

我们有以下数据

id xid 
-- --- 
1  2   
2  3   
Run Code Online (Sandbox Code Playgroud)

以下 select 语句返回布尔值。

select exists(select * from foo where xid=4);

exists
boolean
------
f

select exists(select * from foo where xid=3);

exists
boolean
------
t
Run Code Online (Sandbox Code Playgroud)

好的,现在我们需要返回YESandNO而不是tand f,所以我们可以创建一个自定义类型,如下所示

create type bool2yesno as enum ('YES','NO'); --or whatever you want 'yes','no'.
Run Code Online (Sandbox Code Playgroud)

并创建一个函数将布尔值转换为创建的自定义类型,即bool2yesno

create function convert_bool_to_bool2yesno(boolean)
  returns bool2yesno
  immutable
  strict
  language sql
as $func$
  select case $1
    when false then 'NO'::bool2yesno
    when true  then 'YES'::bool2yesno
  end
$$;
Run Code Online (Sandbox Code Playgroud)

cast现在为新创建的类型创建一个

create cast (boolean as bool2yesno )
  with function convert_bool_to_bool2yesno(boolean)
  as assignment;
Run Code Online (Sandbox Code Playgroud)

现在再次尝试 select 语句

select exists(select * from foo where xid=4)::bool2yesno ;

exists 
bool2yesno 
----------
NO     

select exists(select * from foo where xid=3)::bool2yesno ; 
exists 
bool2yesno 
---------- 
YES 
Run Code Online (Sandbox Code Playgroud)

参考:
CREATE TYPE
CREATE CAST
CREATE FUNCTION


Ser*_*off 6

结束了这个:

(case when credit_card_holders.token IS NOT NULL then 'Yes' else 'No' end) AS premium
Run Code Online (Sandbox Code Playgroud)


And*_*nko -1

有了这个 gem humanize_boolean你可以这样做

true.humanize # => "Yes" false.humanize # => "No"