2

I have the following table in PostgreSQL:

enter image description here

id and grade are INTs, note and subject both VARCHARs

When I run the command:

SELECT * FROM grades 
WHERE subject = "latin";

I get the following error:

In pgAdmin4: ERROR: column "latin" does not exist LINE 2: WHERE subject = "latin" ^ SQL state: 42703 Character: 37

And in cmd: ERROR: column "latin" does not exist LINE 1: SELECT * FROM upisi WHERE subject = "latin";

I'm coming from MySQL so I thought this would work. Works fine if I put grade = something in the WHERE clause. Any idea why this might be the case?

4

2 回答 2

2

字符常量需要单引号。(双引号用于引用标识符)


SELECT * FROM grades 
WHERE subject = 'latin';

如果您使用WHERE subject = "latin",则 DBMS 期望“latin”是一个列名,但事实并非如此。

于 2021-01-26T11:28:31.010 回答
1

这就像错误类型的引号一样简单。你自找的:

SELECT * FROM grades 
WHERE subject = 'latin';

解释:

  • 单引号,如'latin',是在标准 SQL 中编写字符串的标准方式,应该适用于所有 DBMS。
  • 在 Postgres 和其他一些 DBMS 中,双引号是引用标识符的一种方式- 所以如果你的列名由于某种原因有一个空格(没有太多好的理由这样做,但它是可能的),那么你可能会写SELECT * FROM grades WHERE "subject name" = 'latin'-"subject name"是列的名称,'latin'是一个字符串。

尽管双引号在 SQL 标准中,但其他 DBMS 使用不同的语法来引用标识符,因此可以将双引号视为编写字符串的替代方法。

-- Postgres (also works in Microsoft SQL Server, but isn't the default style)
SELECT * FROM grades WHERE "subject name" = 'latin'
-- MySQL
SELECT * FROM grades WHERE `subject name` = 'latin'
-- Microsoft SQL Server
SELECT * FROM grades WHERE [subject name] = 'latin'

但是,如果您总是对字符串使用单引号,并避免使用需要引用的名称,那么您会遇到更少的问题。

-- Works pretty much everywhere
SELECT * FROM grades WHERE subject = 'latin'
于 2021-01-26T11:33:32.250 回答