SQL错误:滥用聚合

时间:2009-03-15 16:29:41

标签: sql sqlite

SQLite版本3.4.0 聚合函数有什么问题?另外,我怀疑ORDER BY不会起作用。如何改写这个?

sqlite> SELECT p1.domain_id, p2.domain_id, COUNT(p1.domain_id) AS d1, COUNT(p2.domain_id) AS d2
   ...> FROM PDB as p1, Interacting_PDBs as i1, PDB as p2, Interacting_PDBs as i2
   ...> WHERE p1.id = i1.PDB_first_id
   ...> AND p2.id = i2.PDB_second_id
   ...> AND i1.id = i2.id
   ...> AND d1>100
   ...> AND d2>100
   ...> ORDER BY d1, d2;
SQL error: misuse of aggregate: 
sqlite>

3 个答案:

答案 0 :(得分:65)

使用聚合函数(sum / count / ...)时,还必须使用GROUP BY子句。

接下来,如果要过滤聚合的结果,则不能在WHERE子句中执行此操作,但必须在HAVING子句中执行此操作。

SELECT p1.domain_id, p2.domain_id, COUNT(p1.domain_id) AS d1, COUNT(p2.domain_id) AS d2
    FROM PDB as p1, Interacting_PDBs as i1, PDB as p2, Interacting_PDBs as i2
    WHERE p1.id = i1.PDB_first_id
    AND p2.id = i2.PDB_second_id
    AND i1.id = i2.id
GROUP BY p1.domain_Id, p2.domain_Id
HAVING d1 > 100 AND d2 > 100
ORDER BY d1, d2;

答案 1 :(得分:4)

对此的短版本修复是:

当您使用COUNT/SUM等功能时,需要使用HAVING代替WHERE

答案 2 :(得分:0)

还请确保您不要将正在使用COUNT / SUM的列之一用于WHERE子句。确保对这些变量使用HAVING而不是WHERE。