问题
we aware strange behavior of H2 when querying COUNT with a subquery.
Prepare table:
CREATE TABLE Foo
(
id INT PRIMARY KEY AUTO_INCREMENT,
fieldName VARCHAR(30) NOT NULL,
);
Test simple query (works fine):
SELECT F1.id, F2.id from Foo as F1 INNER JOIN Foo F2 on F1.id = F2.id
Test same query with count:
SELECT count(*) FROM (
SELECT F1.id, F2.id from Foo as F1 INNER JOIN Foo F2 on F1.id = F2.id
) q;
Got following error:
[42S21][42121] Duplicate column name "ID"; SQL statement: select count(*) FROM (
Any workarounds?
UPDATED: The problem was in that original table name erased when preparing subquery column names and in fact I have :
SELECT count(*) FROM (
SELECT id, id from q
);
Adding alias (as mentioned by Abdul Rasheed) fix the problem.
回答1:
I don't understand why to use the same field and the same table with aliases. Why don't you use simply a query like that :
SELECT count(id) FROM Foo
回答2:
This problem isn't stricly H2 related, but happens in all SQL databases. A top-level SQL SELECT statement is allowed to project two columns by the same name, but a subquery - in particular a derived table - is not. This is irrespective of the fact whether the ambiguous column name from the subquery is ever referenced.
The solution is to explicitly alias your columns:
SELECT count(*) FROM (
SELECT f1.id AS f1_id, f2.id AS f2_id
FROM foo AS f1
INNER JOIN foo f2 ON f1.id = f2.id
) q;
Or to avoid the projection in the derived table entirely, as you're not going to need it to calculate the count value:
SELECT count(*) FROM (
SELECT 1
FROM foo AS f1
INNER JOIN foo f2 ON f1.id = f2.id
) q;
At this point, you could obviously just avoid the derived table completely:
SELECT count(*)
FROM foo AS f1
INNER JOIN foo f2 ON f1.id = f2.id;
An alternative when using H2 1.4.198 or later is to use window functions to calculate the count value on each row:
SELECT f1.id AS f1_id, f2.id AS f2_id, count(*) OVER ()
FROM foo AS f1
INNER JOIN foo f2 ON f1.id = f2.id
来源:https://stackoverflow.com/questions/47282769/count-with-subquery-fail-on-h2-database-with-duplicate-column-name