我不知道为什么下面的查询在 MySQL 中运行得很好,但在 PostgreSQL 中却不行。
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。但后来我得到了另一个结果。
问候。
最佳答案
由于以下原因,这在 mysql 中是可能的
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.
查看此链接中的文档 https://dev.mysql.com/doc/refman/5.5/en/group-by-handling.html
其他 DBMS 可能不会扩展 GROUP BY 的标准 SQL 使用,因此其他 DBMS 中的选择列表只能引用聚合列
即 在其他 DBMS 中此查询
SELECT COUNT(*) Anzahl, PID, postID
FROM PersonLikesPost
GROUP BY (postID)
必须翻译成这样
SELECT COUNT(*) Anzahl, PID, postID
FROM PersonLikesPost
GROUP BY Anzahl, PID, postID
希望这有帮助。
关于mysql - SQL COUNT(*) 在 PostgreSQL 中不起作用,但在 MySQL 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37729254/