SQLite 中的奇怪 "misuse of aggregate: max()" 错误

Strange "misuse of aggregate: max()" error in SQLite

我有 SQLite table,结构非常简单:

CREATE TABLE `test` ( `id` INTEGER, `val` TEXT )

我只想 select 最大 ID,其中 val 字段值等于字符串 "test_id":

SELECT max(id) AS test_id FROM test WHERE val = "test_id"  // (1)

请注意,我在 WHEREtest_id 中使用了“test_id”字符串作为自定义列名称。我得到错误:

misuse of aggregate: max(): SELECT max(id) AS test_id FROM test WHERE val = "test_id"

如果我将 max(id) AS test_id 更改为 max(id) AS test_id2 或将 WHERE val = "test_id" 更改为 WHERE val = "test_id_something" - 一切正常。

在 MySQL 中,我与原始 SELECT (1) 没有任何错误。更正后的版本适用于。 我做错了什么?是否不允许在 WHERE 中使用相同的文本作为 SQLite 中的列名?

您已经回答了自己的问题

If I change max(id) AS test_id to max(id) AS test_id2 or WHERE val = "test_id" to WHERE val = "test_id_something" - all works.

WHERE val = "test_id" 引用 max(id) AS test_id。您需要使用不同的名称。试试这个

SELECT max(id) AS max_id FROM test WHERE val = "some_value"

misuse of aggregate: max():是使用聚合函数的正常结果(AVGCOUNTMINMAXSUM.. .) 在 WHERE 子句中

http://sqlfiddle.com/#!7/b28b3/11

在SQL中,双引号用来引用column/table名字,test_id确实是一个列名。字符串用单引号分隔:

SELECT max(id) AS test_id FROM test WHERE val = 'test_id'

SQLite 允许对字符串使用双引号,以便与 MySQL 进行错误兼容,但如有疑问,它必须选择标准解释。