mysql - SQL COUNT(*) 在 PostgreSQL 中不起作用,但在 MySQL 中不起作用

标签 mysql sql database postgresql group-by

我不知道为什么下面的查询在 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/

相关文章:

mysql - 在mysql中存储持续时间

mysql - 通过 Entity Framework 将具有指定主键的记录插入 MySQL

php - 像 % 在 sql 中有很多值

python - 嵌套的 json 字段上的 Django order_by

mysql - 如何在mysql中将句子拆分为单词

mysql - 按与纬度和经度的接近程度对 WordPress 帖子进行排序

sql - 为什么我的 DLookup 生成 "invalid use of null"错误 : 94

mysql - 数据库更新后如何清除缓存?

mysql - 错误: No unique index found for the referenced field of the primary table

php - 从数据库中获取变量名