【问题标题】:Output "yes/no" instead of "t/f" for boolean data type in PostgreSQL在 PostgreSQL 中为布尔数据类型输出“yes/no”而不是“t/f”
【发布时间】:2015-03-10 08:55:12
【问题描述】:

如何进行查询以返回 yes/no 而不是 t/f(真/假)?

目前的解决方案是:

SELECT credit_card_holders.token IS NOT NULL AS premium

我找到了一个 Ruby 解决方案: Rails (or Ruby): Yes/No instead of True/False

但如果可能的话,宁愿在 PostgreSQL 中做。

【问题讨论】:

  • 你真的需要sql查询返回“是”还是“否”?你不能只使用辅助方法或模型方法将布尔值转换为所需的字符串吗?

标签: sql postgresql boolean


【解决方案1】:

这样结束了:

(case when credit_card_holders.token IS NOT NULL then 'Yes' else 'No' end) AS premium

【讨论】:

    【解决方案2】:

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

    create table foo (id int,xid int);
    insert into foo values (1,2),(2,3);
    

    我们有以下数据

    id xid 
    -- --- 
    1  2   
    2  3   
    

    以下选择语句返回布尔值。

    select exists(select * from foo where xid=4);
    
    exists
    boolean
    ------
    f
    
    select exists(select * from foo where xid=3);
    
    exists
    boolean
    ------
    t
    

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

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

    并创建一个函数将布尔值转换为创建的自定义类型,即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
    $$;
    

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

    create cast (boolean as bool2yesno )
      with function convert_bool_to_bool2yesno(boolean)
      as assignment;
    

    现在再次尝试选择语句

    select exists(select * from foo where xid=4)::bool2yesno ;
    
    exists 
    bool2yesno 
    ----------
    NO     
    
    select exists(select * from foo where xid=3)::bool2yesno ; 
    exists 
    bool2yesno 
    ---------- 
    YES 
    

    参考:
    CREATE TYPE
    CREATE CAST
    CREATE FUNCTION

    【讨论】:

    • 请注意,要为NULL 输出no,需要在convert_bool_to_bool2yesno 函数定义中删除strict 属性。
    【解决方案3】:

    如果真/假足够好,最直接的方法:

    SELECT (credit_card_holders.token IS NOT NULL)::text AS premium
    

    至少它比 t/f 更具可读性!

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多