我有一个相当大的MYSQL数据库,我需要对所有发票进行平均,然后查询这些平均值的最高值。我的查询将连接三个表以获取正确的数据以供显示。表格是品牌,产品和线条。我需要的列是brand_name和brand_id来自品牌,line_price来自行,产品加入了品牌和库存表。
SELECT brand.brand_id, brand.brand_name, brand.brand_type, ROUND(MAX(line_price),2) AS 'Highest AVG Price'
FROM (SELECT brand.brand_id, brand_name, brand_type, AVG(line_price) AS line_price FROM product, brand, line
WHERE product.prod_sku = line.prod_sku
AND product.brand_id = brand.brand_id
GROUP BY brand_id)w1, brand
WHERE w1.brand_id = brand.brand_id;
当我运行查询时,我得到了正确的值,但错误的brand_name和brand_id。我究竟做错了什么?
答案 0 :(得分:0)
尝试使用JOIN:
SELECT b.brand_id, b.brand_name, b.brand_type,
ROUND(MAX(line_price),2) AS 'Highest AVG Price'
FROM product p JOIN brand b ON p.brand_id = b.brand_id
JOIN line l ON l.prod_sku = p.prod_sku GROUP BY b.brand_id
如果问题仍然存在,请告诉我。