use*_*921 3 mysql sql postgresql group-by
假设我有这个表:named = the_table ,其结构是:
PostgreSQL:
create table the_table (col3 SERIAL, col2 varchar, col1 varchar, PRIMARY KEY(col3));
Run Code Online (Sandbox Code Playgroud)
MySQL:
create table the_table ( col3 INT NOT NULL AUTO_INCREMENT PRIMARY KEY, col2 varchar(20), col1 varchar(20) )
Run Code Online (Sandbox Code Playgroud)
然后我插入表格:
INSERT INTO the_table (col2,col1) VALUES
('x','a'),
('x','b'),
('y','c'),
('y','d'),
('z','e'),
('z','f');
Run Code Online (Sandbox Code Playgroud)
现在表格如下所示:
col3 | col2 | col1
------+------+------
1 | x | a
2 | x | b
3 | y | c
4 | y | d
5 | z | e
6 | z | f
Run Code Online (Sandbox Code Playgroud)
当我执行此查询时:
select * from the_table group by col2
Run Code Online (Sandbox Code Playgroud)
然后在 mysql 中我得到:
1 x a
3 y c
5 z e
Run Code Online (Sandbox Code Playgroud)
在 postgreSQL 中,我收到错误:
ERROR: column "the_table.col3" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: select * from the_table group by col2;
Run Code Online (Sandbox Code Playgroud)
我的问题:
这个错误是什么意思?什么是聚合函数?
当它在 MySQL 中工作时,为什么它不能在 postgreSQL 中工作?
您需要使用聚合函数:
聚合函数根据一组输入值计算单个结果。
SELECT col2, MIN(col3) AS col3, MIN(col1) AS col1
FROM the_table
GROUP BY col2;
Run Code Online (Sandbox Code Playgroud)
在标准 SQL 中,包含 GROUP BY 子句的查询无法引用选择列表中未在 GROUP BY 子句中命名的非聚合列
和:
MySQL 扩展了 GROUP BY 的使用,以便选择列表可以引用未在 GROUP BY 子句中命名的非聚合列。这意味着前面的查询在MySQL中是合法的。您可以使用此功能避免不必要的列排序和分组,从而获得更好的性能。然而,这主要是当每个组中未在 GROUP BY 中命名的每个非聚合列中的所有值对于每个组都相同时非常有用。服务器可以自由地从每个组中选择任何值,因此除非它们相同,否则选择的值是不确定的
因此,对于没有显式聚合函数的 MySQL 版本,您可能会得到不确定的值。我强烈建议使用特定的聚合函数。
编辑:
SQL92 及更早版本不允许查询的选择列表、HAVING 条件或 ORDER BY 列表引用未在 GROUP BY 子句中命名的非聚合列。
如果 SQL99 及更高版本在功能上依赖于 GROUP BY 列,则每个可选功能 T301 允许此类非聚合:如果 name 和 custid 之间存在此类关系,则查询是合法的。例如,如果 custid 是客户的主键,就会出现这种情况。
例子:
SELECT o.custid, c.name, MAX(o.payment)
FROM orders AS o
JOIN customers AS c
ON o.custid = c.custid
GROUP BY o.custid;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4050 次 |
| 最近记录: |