【问题标题】:Select date (timestamp) from PostgreSQL as string (char), beware of NULL value从 PostgreSQL 中选择日期(时间戳)作为字符串(字符),注意 NULL 值
【发布时间】:2013-04-06 02:26:02
【问题描述】:

我想选择一个日期(我的列是时间戳类型)。但是当列中的日期为 NULL 时,我想返回一个空字符串。这个怎么做?我是这样写的:

SELECT
   CASE WHEN to_char(last_post, 'MM-DD-YYYY HH24:MI:SS') IS NULL THEN ''
      ELSE to_char(last_post, 'MM-DD-YYYY HH24:MI:SS') AS last_post END
   to_char(last_post, 'MM-DD-YYYY HH24:MI:SS') AS last_post, content
FROM topic;

但它显示了一些错误,不知道为什么:

ERROR:  syntax error at or near "as"
LINE 1: ...ELSE to_char(last_post, 'MM-DD-YYYY HH24:MI:SS') AS last_po...
                                                            ^

【问题讨论】:

    标签: sql postgresql select postgresql-9.1


    【解决方案1】:

    使用COALESCE() 函数是最好的方法,因为它只是在NULL 的情况下交换一个替代值。可读性也大大提高。 :)

    SELECT COALESCE(to_char(last_post, 'MM-DD-YYYY HH24:MI:SS'), '') AS last_post, content FROM topic;
    

    【讨论】:

      【解决方案2】:
      select coalesce(to_char(last_post, 'MM-DD-YYYY HH24:MI:SS'), '') as last_post, content
      from topic;
      

      【讨论】:

        【解决方案3】:

        你要把你的AS 放在箱子里吗?

        试试:

        SELECT
           CASE WHEN last_post IS NULL THEN ''
             ELSE to_char(last_post, 'MM-DD-YYYY HH24:MI:SS') END AS last_post,
           content
        FROM topic;
        

        我还没有尝试过查询。

        【讨论】:

        • 这个可以简化为case when last_post is null then '' else ...
        • @a_horse_with_no_name 你说得对,谢谢!我只专注于稍后移动AS ...,并没有考虑简化查询...我现在就解决这个问题!
        猜你喜欢
        • 2011-04-06
        • 2015-12-28
        • 1970-01-01
        • 2021-06-27
        • 1970-01-01
        • 2012-10-25
        • 1970-01-01
        • 1970-01-01
        • 2017-07-02
        相关资源
        最近更新 更多