解決 MySQL 中的錯誤 1111 (HY000):在組函式中使用無效?如何正確與 where 子句結合使用聚合函式?


若要在 MySQL 中正確地與 where 子句結合使用聚合函式,語法如下 −

select *from yourTableName
where yourColumnName > (select AVG(yourColumnName) from yourTableName);

為了理解上述概念,讓我們建立一個表格。建立表格的查詢如下 −

mysql> create table EmployeeInformation
   -> (
   -> EmployeeId int,
   -> EmployeeName varchar(20),
   -> EmployeeSalary int,
   -> EmployeeDateOfBirth datetime
   -> );
Query OK, 0 rows affected (1.08 sec)

現在,可以使用 insert 命令在表格中插入一些記錄。查詢如下 −

mysql> insert into EmployeeInformation values(101,'John',5510,'1995-01-21');
Query OK, 1 row affected (0.13 sec)
mysql> insert into EmployeeInformation values(102,'Carol',5600,'1992-03-25');
Query OK, 1 row affected (0.56 sec)
mysql> insert into EmployeeInformation values(103,'Mike',5680,'1991-12-25');
Query OK, 1 row affected (0.14 sec)
mysql> insert into EmployeeInformation values(104,'David',6000,'1991-12-25');
Query OK, 1 row affected (0.23 sec)
mysql> insert into EmployeeInformation values(105,'Bob',7500,'1993-11-26');
Query OK, 1 row affected (0.16 sec)

使用 select 語句顯示錶格中的所有記錄。查詢如下 −

mysql> select *from EmployeeInformation;

輸出如下 −

+------------+--------------+----------------+---------------------+
| EmployeeId | EmployeeName | EmployeeSalary | EmployeeDateOfBirth |
+------------+--------------+----------------+---------------------+
|        101 | John         |           5510 | 1995-01-21 00:00:00 |
|        102 | Carol        |           5600 | 1992-03-25 00:00:00 |
|        103 | Mike         |           5680 | 1991-12-25 00:00:00 |
|        104 | David        |           6000 | 1991-12-25 00:00:00 |
|        105 | Bob          |           7500 | 1993-11-26 00:00:00 |
+------------+--------------+----------------+---------------------+
5 rows in set (0.00 sec)

以下是與 where 子句結合使用聚合的正確方式。查詢如下 −

mysql> select *from EmployeeInformation
   -> where EmployeeSalary > (select AVG(EmployeeSalary) from EmployeeInformation);

輸出如下 −

+------------+--------------+----------------+---------------------+
| EmployeeId | EmployeeName | EmployeeSalary | EmployeeDateOfBirth |
+------------+--------------+----------------+---------------------+
|        105 | Bob          |           7500 | 1993-11-26 00:00:00 |
+------------+--------------+----------------+---------------------+
1 row in set (0.04 sec)

更新於: 30-07-2019

2K+ 瀏覽量

啟動你的職業

透過完成課程取得認證

開始使用
廣告
© . All rights reserved.