Question

Puis-je combiner ces 2 instructions SQL? Actuellement en cours d'exécution 2 requêtes. Essayer de resserrer un peu.

Premier:

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

Deuxième:

SELECT ROUND(AVG(rating)) as avg_rating
FROM car_ratings WHERE car_id = 185707 
Était-ce utile?

La solution

Vous pouvez le faire en utilisant groupe par :

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 c'est une extension de MySQL au standard SQL ; en SQL standard, vous devez répertorier tous les champs sélectionnés dans le groupe par la clause .

Autres conseils

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 ou non une amélioration est une autre question, il vaut mieux y répondre en consultant le plan de requête utilisé.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top