Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lararocks's avatar

Help with query

Hello,

Sorry I'm not excellent in SQL and I need to write a plain sql query to get me the top 5 rated places by calculating the average rating for all services.

My tables

PLACE Table

  • id
  • country_id
  • is_active
  • name

RATING

  • id
  • place_id
  • service_id
  • rating

I tried the below but it throws an error:

$sql = "SELECT p.id as id, p.name as name, avg(r.rating) as rating FROM place p, rating r WHERE r.place_id = p.id AND p.country_id = 99 AND p.is_active = 1 GROUP BY r.place_id"; $results = DB::select($sql);

0 likes
4 replies
Tray2's avatar
Tray2
Best Answer
Level 73
SELECT p.name, (SELECT avg(r.rating) FROM ratings r WHERE r.place_id = p.id) rating FROM places p WHERE  p.country_id = 99 AND p.is_active = 1 

Should work unless I made a type-o.

1 like
Tray2's avatar

Add

 order by (SELECT avg(r.rating) FROM ratings r WHERE r.place_id = p.id) desc limit 5
1 like

Please or to participate in this conversation.