我在 PostgreSQL 中有以下查询:
SELECT
COUNT(a.log_id) AS overall_count
FROM
"Log" as a,
"License" as b
WHERE
a.license_id=7
AND
a.license_id=b.license_id
AND
b.limit_call > overall_count
GROUP BY
a.license_id;
为什么会出现此错误:
ERROR: column "overall_count" does not exist
我的表结构:
License(license_id, license_name, limit_call, create_date, expire_date)
Log(log_id, license_id, log, call_date)
我想检查许可证是否已达到特定月份的调用限制。
最佳答案
SELECT a.license_id, a.limit_call
, count(b.license_id) AS overall_count
FROM "License" a
LEFT JOIN "Log" b USING (license_id)
WHERE a.license_id = 7
GROUP BY a.license_id -- , a.limit_call -- add in old versions
HAVING a.limit_call > count(b.license_id)
自 Postgres 9.1 以来,主键涵盖了 GROUP BY
中表的所有列。条款。在旧版本中,您必须添加 a.limit_call
到 GROUP BY
列表。 release notes for 9.1 :
Allow non-
GROUP BY
columns in the query target list when the primary key is specified in theGROUP BY
clause
进一步阅读:
您在 WHERE
中的情况子句必须移动到 HAVING
子句,因为它引用聚合函数的结果(在 WHERE
已应用)。并且您不能在 HAVING
中引用输出列(列别名)子句,您只能在其中引用输入列。所以你必须重复这个表达。 The manual:
An output column's name can be used to refer to the column's value in
ORDER BY
andGROUP BY
clauses, but not in theWHERE
orHAVING
clauses; there you must write out the expression instead.
我颠倒了 FROM
中表格的顺序子句并稍微清理了语法以减少混淆。 <强> USING
在这里只是为了方便记号。
我用了 LEFT JOIN
而不是 JOIN
,因此您根本不会排除没有任何日志的许可证。
count()
只计算非空值.因为你想计算表 "Log"
中的相关条目使用 count(b.license_id)
更安全也更便宜强>。该列用于连接,因此我们不必担心该列是否可以为空。
count(*)
甚至更短,更快,然而。如果你不介意得到 1
的计数对于 0
左表中的行,使用它。
另外:我建议不要使用mixed case identifiers如果可能,在 Postgres 中。非常容易出错。
关于sql - PostgreSQL Where 计数条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8119489/