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

Postgres: why do I need to quote column name in max()?

所以我遇到了以下让我感到惊讶的行为。我首先想到 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)

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

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

您创建的 table 应如下所示:

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