Aggregate function in order by and apply to the result of non-aggregated query gives error in Mysql
- Dominant language
- Go
- Stars
- 40.5k
- Forks
- 6.2k
- PR merge metrics
- PR metrics pending
Description
## Bug Report
Please answer these questions before submitting your issue. Thanks!
### 1. Minimal reproduce step (Required)
```sql
drop table if exists t1;
CREATE TABLE t1 (a INT);
INSERT INTO t1 values (),(),();
SELECT (SELECT SLEEP(0) FROM t1 ORDER BY AVG(DISTINCT a) ) as x FROM t1 GROUP BY x;
SELECT 1 FROM t1 GROUP BY (SELECT SLEEP(0) FROM t1 ORDER BY AVG(DISTINCT a) );
```
### 2. What did you expect to see? (Required)
```sql
mysql> CREATE TABLE t1 (a INT);
Query OK, 0 rows affected (0.02 sec)
mysql> INSERT INTO t1 values (),(),();
Query OK, 3 rows affected (0.01 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT (SELECT SLEEP(0) FROM t1 ORDER BY AVG(DISTINCT a) ) as x FROM t1 GROUP BY x;
ERROR 3029 (HY000): Expression #1 of ORDER BY contains aggregate function and applies to the result of a non-aggregated query
mysql> SELECT 1 FROM t1 GROUP BY (SELECT SLEEP(0) FROM t1 ORDER BY AVG(DISTINCT a) );
ERROR 3029 (HY000): Expression #1 of ORDER BY contains aggregate function and applies to the result of a non-aggregated query
```
### 3. What did you see instead (Required)
```sql
mysql> CREATE TABLE t1 (a INT);
Query OK, 0 rows affected (0.01 sec)
mysql> INSERT INTO t1 values (),(),();
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT (SELECT SLEEP(0) FROM t1 ORDER BY AVG(DISTINCT a) ) as x FROM t1 GROUP BY x;
+------+
| x |
+------+
| 0 |
+------+
1 row in set (0.00 sec)
mysql> SELECT 1 FROM t1 GROUP BY (SELECT SLEEP(0) FROM t1 ORDER BY AVG(DISTINCT a) );
+---+
| 1 |
+---+
| 1 |
+---+
1 row in set (0.01 sec)
```
### 4. What is your TiDB version? (Required)
```sql
| Release Version: v6.2.0-alpha-103-g395ccbe22
Edition: Community
Git Commit Hash: 395ccbe22d5e0d0f6412f33d9bbf8d90fe52cc66
Git Branch: master
UTC Build Time: 2022-06-13 17:05:18
GoVersion: go1.18
Race Enabled: false
TiKV Min Version: v3.0.0-60965b006877ca7234adaced7890d7b029ed1306
Check Table Before Drop: false
Store: unistore |
```
Contributor guide
Assessment
This issue has not been assessed yet.