Docker PSQL 查询问题:"Column <column_name> does not exist"

Docker PSQL Query Issue: "Column <column_name> does not exist"

我正在尝试通过 shell 脚本中的 docker 内联命令执行数据库查询。

myscript.sh:

docker run -it --rm -c "psql -U ${DB_USER} -d ${DB_NAME} -h ${DB_HOST}\
    -c 'select col1, col2 , col3 from table1\
    where table1.col2 = \"matching_text\" order by col1;'"

但是我得到一个奇怪的错误:

ERROR:  column "matching_text" does not exist
LINE 1: ...ndow where table1.col2 = "matching_t...

出于某种原因,当我 运行 这个时,psql 认为我查询中的 matching_text 指的是列名。我该如何解决这个问题?

注意:我们的数据库是作为 psql docker 容器实现的。

Postgres 手册说明您需要使用单引号:

A string constant in SQL is an arbitrary sequence of characters bounded by single quotes ('), for example 'This is a string'. To include a single-quote character within a string constant, write two adjacent single quotes, e.g., 'Dianne''s horse'. Note that this is not the same as a double-quote character (").

section 4.1.2.1 of the postgres manual

双引号用于 table 或列标识符:

There is a second kind of identifier: the delimited identifier or quoted identifier. It is formed by enclosing an arbitrary sequence of characters in double-quotes ("). A delimited identifier is always an identifier, never a key word. So "select" could be used to refer to a column or table named "select", whereas an unquoted select would be taken as a key word and would therefore provoke a parse error when used where a table or column name is expected. The example can be written with quoted identifiers like this:

UPDATE "my_table" SET "a" = 5;

参见同一手册的第 4.1.1 节。

这里 post 和其他 post 的组合解决了这个问题:

  1. 字符串查询需要使用单引号
  2. 在 psql 命令中对 -c 使用双引号 ()
docker run -it --rm -c "psql -U ${DB_USER} -d ${DB_NAME} -h ${DB_HOST}\
    -c \"select col1, col2 , col3 from table1\
    where table1.col2 = 'matching_text' order by col1;\""