我有以下数据库架构:
Customer(ssn, name, gender, city)
Vehicle(vin, make, model, year)
BuyVehicle(bvssn, bvvin, price, year)
其中BuyVehicle.bvvin
是来自Vehicle.vin
的外键,而BuyVehicle.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;
我试图在price > avg_price
子句中输入WHERE
条件:
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;
但是MySQL告诉我avg_price
列不存在。我对这个问题采取了错误的方法吗?
答案 0 :(得分:4)
你需要使用:
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
答案 1 :(得分:0)
使用聚合时,你需要使用一个名为'HAVING'的单独子句,该子句位于group by之后,但看起来你要编写的查询实际上比这更复杂。
你想在结果中看到什么?
我怀疑你需要针对一个子查询做一个平均值来得到我猜你想要的东西