2009-10-26 5 views
0

Puis-je combiner ces 2 instructions SQL? En cours d'exécution 2 requêtes. J'essaie de me resserrer un peu.MySQL - Puis-je combiner ces 2 instructions SQL? Combiner JOIN et AVG?

premier:

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

seconde:

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

Répondre

3

Vous pouvez le faire en utilisant 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 

Notez que this is a MySQL extension to standard SQL; En SQL standard, vous devez répertorier tous les champs sélectionnés dans la clause 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 

Mais si cela représente une amélioration est une autre question, la meilleure réponse en voyant ce plan de requête est utilisé.