Postgres:为什么我需要在max()中引用列名?

时间:2019-05-29 12:52:31

标签: sql postgresql quoted-identifier

所以我遇到了以下令我惊讶的行为。我首先想到 DateTime 可能是postgres数据类型,但是BidOpen呢?然后在错误消息中有一个有趣的事情,就是列名的情况。我几乎觉得这与不带引号的名称不区分大小写有关。 为什么要使查询生效,我需要在列名两边加上引号吗?

mydatabase=# select max("DateTime") from fx.candle;
         max
---------------------
 2019-04-26 20:59:00
(1 row)

mydatabase=# select max(DateTime) from fx.candle;
ERROR:  column "datetime" does not exist
LINE 1: select max(DateTime) from fx.candle;
                   ^
HINT:  Perhaps you meant to reference the column "candle.DateTime".
mydatabase=# select max(BidOpen) from fx.candle;
ERROR:  column "bidopen" does not exist
LINE 1: select max(BidOpen) from fx.candle;
                   ^
HINT:  Perhaps you meant to reference the column "candle.BidOpen".
mydatabase=# select max("BidOpen") from fx.candle;
   max
---------
 125.816
(1 row)

模式如下:

mydatabase=# \d fx.candle;
                                        Table "fx.candle"
  Column   |            Type             |                            Modifiers
-----------+-----------------------------+-----------------------------------------------------------------
 id        | integer                     | not null default nextval('fx.candle_id_seq'::regclass)
 DateTime  | timestamp without time zone |
 BidOpen   | double precision            | not null
 BidHigh   | double precision            | not null
 BidLow    | double precision            | not null
 BidClose  | double precision            | not null
 AskOpen   | double precision            | not null
 AskHigh   | double precision            | not null
 AskLow    | double precision            | not null
 AskClose  | double precision            | not null
 symbol_id | integer                     |
Indexes:
    "candle_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "candle_symbol_id_fkey" FOREIGN KEY (symbol_id) REFERENCES fx.symbol(id)

1 个答案:

答案 0 :(得分:1)

我的理解是,Postgres对于列和表名称​​ 不区分大小写,除非您实际上在开头使用双引号来创建它们。如果是这种情况,那么您将需要永远使用双引号引用它们,以确保使用正确的大小写文字。

因此,为避免当前情况,还应避免以区分大小写的方式创建列/表名称。

您的创建表应如下所示:

create table fx.candle (
    id integer not null default nextval('fx.candle_id_seq'::regclass),
    ...
    datetime timestamp without time zone   -- NO quotes here; important!
    ...
)