MySQL - 我可以组合这两个SQL语句吗?结合JOIN和AVERAGE?

时间:2009-10-26 21:57:03

标签: sql mysql join average

我可以合并这两个SQL语句吗?目前正在运行2个查询试着收紧一点。

第一个:

SELECT * FROM (`cars`) 
JOIN `brands` ON `brands`.`br_id` = `cars`.`brand_id`
WHERE `cars`.`id` = '185707'

第二个:

SELECT ROUND(AVG(rating)) as avg_rating
FROM car_ratings WHERE car_id = 185707 

2 个答案:

答案 0 :(得分:3)

您可以使用group by

执行此操作
select cars.*,
       brands.*, 
       round(avg(car_ratings.rating)) as avg_rating
from   (cars
    inner join brands on brands.br_id = cars.brand_id)
    left join car_ratings on car_ratings.car_id = cars.id
where  cars.id = 185707
group by cars.id

请注意this is a MySQL extension to standard SQL;在标准SQL中,您需要列出group by子句中的所有选定字段。

答案 1 :(得分:1)

select *

, (select round(avg(rating)) from car_ratings 
where car_id = cars.id) as avg_rating

from cars join brands on brands.br_id = cars.brand_id
where cars.id = 185707

但是,这是否代表了改进是另一个问题,最好通过查看正在使用的查询计划来回答。