这个查询非常简单,但是我在数据库中做了一些错误的事情。
我有以下查询:
SELECT login FROM accounts WHERE login = "loginname";
当我执行这个查询时,得到的结果如下:
column "loginname" does not exist
这非常简单,为什么这个查询不能正常工作?我有一个登录列,我知道这个用户存在,因为我在Rails控制台中找到了这个人。为什么登录条件将自身称为列?
这个查询非常简单,但是我在数据库中做了一些错误的事情。
我有以下查询:
SELECT login FROM accounts WHERE login = "loginname";
column "loginname" does not exist
如果您正在尝试匹配一个字符串,请尝试使用单引号''
SELECT login FROM accounts WHERE login = 'loginname';
双引号 ("
) 用于区分大小写地引用对象名称。在这种情况下,"loginname"
被解释为列名,查询失败,因为没有这样的列。为了引用字符串文字,应使用单引号 ('
):
SELECT login FROM accounts WHERE login = 'loginname';
-- Here ---------------------------------^---------^
如果你相信文档,那么看起来双引号是问题所在。字符串值需要使用单引号。
来自PostgreSQL文档:
所以在你的查询中,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;
Quoted identifiers can contain any character, except the character with code zero. (To include a double quote, write two double quotes.) This allows constructing table or column names that would otherwise not be possible, such as ones containing spaces or ampersands. The length limitation still applies.
"loginname"
和没有引号的 loginname
是一样的 - 它试图引用该名称的列。要将其变成字面字符串,请改用单引号。
SELECT login FROM accounts WHERE login = 'loginname';
- Lukasz Szozda