MySQL WHERE子句中的聚合?

Chr*_*gis 2 mysql

我有以下数据库架构:

Customer(ssn, name, gender, city)
Vehicle(vin, make, model, year)
BuyVehicle(bvssn, bvvin, price, year)
Run Code Online (Sandbox Code Playgroud)

哪里BuyVehicle.bvvin是一个外键Vehicle.vinBuyVehicle.bvssn是从一个外键Customer.ssn。我正在尝试选择以高于特定车辆平均价格的价格购买车辆的人的姓名。

到目前为止,我已经确定了如何计算车辆的平均值:

SELECT AVG(price) as avg_price, v.maker, v.model, v.year FROM BuyVehicle bv, Vehicle v, Customer c WHERE v.vin = bv.BVVIN AND c.ssn = bv.bvssn GROUP BY maker, model, year;
Run Code Online (Sandbox Code Playgroud)

我试图price > avg_priceWHERE子句中输入条件:

SELECT AVG(price) as avg_price, v.maker, v.model, v.year FROM BuyVehicle bv, Vehicle v, Customer c WHERE v.vin = bv.BVVIN AND c.ssn = bv.bvssn AND bv.price > avg_price GROUP BY maker, model, year;
Run Code Online (Sandbox Code Playgroud)

但是MySQL告诉我该avg_price列不存在。我是否对这个问题采取了错误的方法?

Nes*_*zon 6

您需要使用具有:

SELECT AVG(price) as avg_price, v.maker, v.model, v.year, bv.price 
FROM BuyVehicle bv, Vehicle v, Customer c WHERE v.vin = bv.BVVIN AND c.ssn = bv.bvssn
GROUP BY maker, model, year
having bv.price > avg_price
Run Code Online (Sandbox Code Playgroud)