2016-06-09 60 views
0

我不知道为什么以下查询在MySQL中完美,但在PostgreSQL中不起作用。SQL COUNT(*)在PostgreSQL中不起作用,但是在MySQL中

SELECT MAX(Anzahl) max_cnt, PID 
FROM (
SELECT COUNT(*) Anzahl, PID, postID 
FROM PersonLikesPost 
GROUP BY (postID) 
ORDER BY Anzahl DESC) as d 

PostgreSQL说,我需要在GROUP BY子句中的PID。但是,我得到了另一个结果。

问候。

+3

它在MySQL中起作用,因为默认情况下它允许请求不一致的结果。修复查询,它会在任一DBMS中工作。 –

回答

2

这是可能的,因为以下

MySQL extends the standard SQL use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. This means that the preceding query is legal in MySQL. You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate. Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause. Result set sorting occurs after values have been chosen, and ORDER BY does not affect which values within each group the server chooses.

的MySQL的在这个链接看看文档https://dev.mysql.com/doc/refman/5.5/en/group-by-handling.html

其他DBMS可能不扩展标准SQL使用GROUP BY的这样的选择列表中的其他DBMS只能引用聚集列

即在其他DBMS 此查询

SELECT COUNT(*) Anzahl, PID, postID 
FROM PersonLikesPost 
GROUP BY (postID) 

已被翻译成这个

SELECT COUNT(*) Anzahl, PID, postID 
    FROM PersonLikesPost 
    GROUP BY Anzahl, PID, postID 

希望这有助于。

+0

Sybase也具有与标准相似的扩展名... – Shadow

+0

此查询也不起作用。 现在PostgreSQL说: 错误:在GROUP BY中不允许使用聚合函数。 – wir12flb

相关问题