MySQL - Can I combine these 2 SQL statements? Combine JOIN and AVG?

天涯浪子 提交于 2019-12-12 01:42:46

问题


Can I combine these 2 SQL statements? Currently running 2 queries. Trying to tighten up a bit.

First one:

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

Second one:

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

回答1:


You can do this using 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

Note that this is a MySQL extension to standard SQL; in standard SQL you would need to list all of the selected fields in the group by clause.




回答2:


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

But whether or not that represents an improvement is another question, best answered by seeing what query plan is being used.



来源:https://stackoverflow.com/questions/1627567/mysql-can-i-combine-these-2-sql-statements-combine-join-and-avg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!