Bug #121644 Incorrect ERROR 1054 for a qualified GROUP BY column referenced in HAVING
Description:
MySQL Community Server 9.7.1 rejects a valid grouped SELECT with `ERROR 1054: Unknown column 'a.c2' in 'having clause'`. The column exists and is explicitly included in `GROUP BY`. Both input tables expose a column named `c2`, and both qualified columns appear in `GROUP BY`, but `a.c2` is not projected by SELECT.
The reduced reproduction uses two single-column temporary tables and three rows. It requires no indexes, window functions, correlated subqueries, or persistent data changes. The error also occurs with `EXPLAIN` and after disabling `ONLY_FULL_GROUP_BY`. Adding `a.c2` to SELECT or giving that input column a distinct name makes the query succeed.
This is an incorrect rejection of a valid query: a grouping column may be referenced in HAVING without appearing in SELECT, and the qualifier `a` identifies the intended input column. The observations point to a HAVING name-resolution defect; the internal implementation cause has not been established.
## Expected behaviour
The join produces `(a.c2, b.c2) = (-1, 10)` and `(1, 10)`. Grouping by both columns creates two groups. HAVING retains only the group with `a.c2 = 1`, so the result should be:
```text
+----+---+
| c2 | n |
+----+---+
| 10 | 1 |
+----+---+
```
Both grouping columns are qualified, and the only nonaggregate SELECT expression, `b.c2`, is explicitly grouped. The query satisfies `ONLY_FULL_GROUP_BY`.
## Actual behaviour
```text
ERROR 1054 (42S22): Unknown column 'a.c2' in 'having clause'
```
PyMySQL reports:
```text
OperationalError(1054, "Unknown column 'a.c2' in 'having clause'")
```
The same error occurs when `EXPLAIN` is prepended to the SELECT.
How to repeat:
CREATE TEMPORARY TABLE valscope_having_a (c2 INT NOT NULL);
CREATE TEMPORARY TABLE valscope_having_b (c2 INT NOT NULL);
INSERT INTO valscope_having_a VALUES (-1), (1);
INSERT INTO valscope_having_b VALUES (10);
SELECT b.c2, COUNT(*) AS n
FROM valscope_having_a AS a
JOIN valscope_having_b AS b ON TRUE
GROUP BY b.c2, a.c2
HAVING a.c2 > 0;
Portions of this website are copyright © 2001, 2002 The PHP Group
Page generated in 0.051 sec. using MySQL 8.4.7-u6-cloud
Timestamp references displayed by the system are UTC.
Content reproduced on this site is the property of the
respective copyright holders.
It is not reviewed in advance
by Oracle and does not necessarily represent the opinion of
Oracle or any other party.