PostgreSQL DBA(186) - SQL Group By

在使用GROUP BY的时候,一般来说GROUP BY后跟分组列,但实际上在PG中可以在GROUP BY后跟表主键。

[local]:5014 pgmaster@testdb=# drop table t;
DROP TABLE
Time: 39.739 ms
[local]:5014 pgmaster@testdb=# create table t(id int primary key,name text,title text);
CREATE TABLE
Time: 59.905 ms
[local]:5014 pgmaster@testdb=# insert into t values(1,'test1','test1');
INSERT 0 1
Time: 5.222 ms
[local]:5014 pgmaster@testdb=# insert into t values(2,'test','test');
INSERT 0 1
Time: 5.223 ms
[local]:5014 pgmaster@testdb=# insert into t values(3,'test','test');
INSERT 0 1
Time: 4.569 ms
[local]:5014 pgmaster@testdb=# select name,count(*) from t group by id;
 name  | count
-------+-------
 test  |     1
 test  |     1
 test1 |     1
(3 rows)
Time: 8.932 ms
[local]:5014 pgmaster@testdb=# select name,count(*) from t group by name;
 name  | count
-------+-------
 test  |     2
 test1 |     1
(2 rows)
Time: 0.906 ms
[local]:5014 pgmaster@testdb=# select name,count(*) from t group by title;
2022-02-11 15:13:15.392 CST [1882] ERROR:  column "t.name" must appear in the GROUP BY clause or be used in an aggregate function at character 8
2022-02-11 15:13:15.392 CST [1882] STATEMENT:  select name,count(*) from t group by title;
ERROR:  column "t.name" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: select name,count(*) from t group by title;
               ^
Time: 0.291 ms
[local]:5014 pgmaster@testdb=#

值得一提的是,在MySQL中,分组列不需要在GROUP BY中,在实际执行的时候MySQL会随机选取GROUP BY分组后该列的一个随机值返回。

参考资料
Functional Dependencies in SQL GROUP BY
group-by-handling

请使用浏览器的分享功能分享到微信等