2009-10-26 96 views
0

我可以合併這兩個SQL語句嗎?目前運行2個查詢。試圖收緊一點。MySQL - 我可以結合這兩個SQL語句嗎?結合JOIN和AVG?

第一招:

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 

回答

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
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 

但不論這是否是一個進步是另一個問題,通過看到的是正在使用的查詢計劃的最好回答。