当我在h2数据库(版本1.3.161)上执行以下sql命令时:
CREATE TABLE Person
(
id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(10)
);
CREATE TABLE Actor
(
id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
PersonId int,
FOREIGN KEY (PersonId) REFERENCES Person(Id)
);
INSERT INTO Person (name) values ('A person');
INSERT INTO Actor ( PERSONID ) values (1);
INSERT INTO Actor ( PERSONID ) values (1);
SELECT ACTOR.ID, ACTOR.PERSONID FROM ACTOR GROUP BY PERSONID ;
我有以下例外:
org.h2.jdbc.JdbcSQLException: Column "ACTOR.ID" must be in the GROUP BY list; SQL statement:
SELECT ACTOR.ID, ACTOR.PERSONID FROM ACTOR GROUP BY PERSONID [90016-161]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:329)
at org.h2.message.DbException.get(DbException.java:169)
at org.h2.message.DbException.get(DbException.java:146)
at org.h2.expression.ExpressionColumn.updateAggregate(ExpressionColumn.java:155)
at org.h2.command.dml.Select.queryGroupSorted(Select.java:183)
at org.h2.command.dml.Select.queryWithoutCache(Select.java:610)
at org.h2.command.dml.Query.query(Query.java:298)
at org.h2.command.dml.Query.query(Query.java:268)
at org.h2.command.dml.Query.query(Query.java:37)
at org.h2.command.CommandContainer.query(CommandContainer.java:82)
at org.h2.command.Command.executeQuery(Command.java:185)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:173)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:152)
at org.h2.server.web.WebApp.getResult(WebApp.java:1311)
at org.h2.server.web.WebApp.query(WebApp.java:1001)
at org.h2.server.web.WebApp$1.next(WebApp.java:964)
at org.h2.server.web.WebApp$1.next(WebApp.java:967)
at org.h2.server.web.WebThread.process(WebThread.java:166)
at org.h2.server.web.WebThread.run(WebThread.java:93)
at java.lang.Thread.run(Thread.java:680)
如果我在MYSQL DB上执行完全相同的命令,它会返回预期的结果:
+----+----------+
| id | PersonId |
+----+----------+
| 1 | 1 |
+----+----------+
答案 0 :(得分:2)
MySQL是唯一允许这样做的数据库。我认为这是MySQL中的一个错误。另请参阅问题Converting MySQL select to PostgreSQL,PostgreSQL GROUP BY different from MySQL?,PostgreSQL -must appear in the GROUP BY clause or be used in an aggregate function。
PostgreSQL抛出以下异常:
ERROR: column "actor.id" must appear in the GROUP BY clause
or be used in an aggregate function
42803/0
Apache Derby引发以下异常:
Column reference 'ACTOR.ID' is invalid, or is part of an invalid expression.
For a SELECT list with a GROUP BY, the columns and expressions being selected
may only contain valid grouping expressions and valid aggregate expressions.
42Y36/30000
(我没有和其他数据库一起测试)