MySQL 中出现错误,错误代码为:1054。'having clause' 中的未知列 'Price'

Getting error in MySQL as Error Code: 1054. Unknown column 'Price' in 'having clause'

我创建了一个 table 如下:

create table products 
(productID int not null auto_increment,
 Name varchar(30),
 Price float ,
 CoffeOrigin varchar(30),
 primary key (productID));

现在的问题是“显示低于平均价的商品名称”

我的第一次尝试:

select Name from products having Price <= avg(Price);

它给我错误代码:1054。'having clause'

中的未知列 'Price'

我的第二次尝试:

select * from products having Price <= avg(Price);

它给我的输出不完整。这里的平均价格是 3.14,但结果中只显示价格小于 3 的产品。

尝试

Select NAME from products
Group by Products, Price
Having price <= AVG(Price) 

列必​​须包含在分组依据中才能正确选择

您想将每一行的价格与整个 table 的平均价格进行比较,因此您不能只使用聚合。您的两次尝试都不是有效的聚合查询。

如果你是运行 MySQL 8.0,你可以直接使用window函数:

select p.*
from (select p.*, avg(price) over() avg_price from products p) p
where price <= avg_price

在早期版本中,一个选项使用标量子查询来计算平均值:

select p.*
from products p
where price <= (select avg(price) from products)