简体   繁体   English

在 MySQL 中获取错误为错误代码:1054。“具有子句”中的未知列“价格”

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

I have created a table as follows:我创建了一个表如下:

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

Now the question is "Display the name of products whose price is less than average price."现在的问题是“显示价格低于平均价格的产品名称”。

My 1st attempt:我的第一次尝试:

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

It is giving me error as Error Code: 1054. Unknown column 'Price' in 'having clause'它给我的错误是错误代码:1054。“具有子句”中的未知列“价格”

My 2nd attempt:我的第二次尝试:

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

It is giving me incomplete output.它给了我不完整的输出。 Here average Price is 3.14 but is only products with price less than 3 are being displayed in the result.这里的平均价格为 3.14,但结果中仅显示价格低于 3 的产品。

Try尝试

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

The columns must be included in a group by in order to be correctly selected列必须包含在一个组中才能被正确选择

You want to compare the price on each row to the average price over the whole table, so you can't just use aggregation.您想将每一行的价格与整个表的平均价格进行比较,因此您不能只使用聚合。 Both your attempts are not valid aggregation queries.您的两次尝试都不是有效的聚合查询。

If you are running MySQL 8.0, you can just use window functions:如果您运行的是 MySQL 8.0,则可以只使用窗口函数:

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

In earlier versions, one option uses a scalar subquery to compute the average:在早期版本中,一个选项使用标量子查询来计算平均值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM