Andrew R Posted September 18, 2009 Share Posted September 18, 2009 Hi Struggling to get my head around this. Basically I have system where users can rate restaurants. I have table containing restaurant info. In another table I have user ratings. What I am trying to do is calculate the average rating of each restaurant and then display the top 5 restaurants with the highest average. What do you recommend is the best way to do this? Calculate the top five averages in user rating and then join it with the restaurant table? Many thanks Quote Link to comment https://forums.phpfreaks.com/topic/174706-solved-how-to-work-top-averages-out/ Share on other sites More sharing options...
Maq Posted September 18, 2009 Share Posted September 18, 2009 Post your table structures. Quote Link to comment https://forums.phpfreaks.com/topic/174706-solved-how-to-work-top-averages-out/#findComment-920727 Share on other sites More sharing options...
Andrew R Posted September 18, 2009 Author Share Posted September 18, 2009 Cheers CREATE TABLE IF NOT EXISTS `resturants` ( `resturant_id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(250) NOT NULL, `info` varchar(500) NOT NULL, `status` int(11) NOT NULL DEFAULT '1', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS `ratings` ( `id` int(11) NOT NULL AUTO_INCREMENT, `resturant_id` int(11) NOT NULL, `rating` int(11) NOT NULL, `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; Quote Link to comment https://forums.phpfreaks.com/topic/174706-solved-how-to-work-top-averages-out/#findComment-920731 Share on other sites More sharing options...
Maq Posted September 18, 2009 Share Posted September 18, 2009 You spelled restaurants wrong. SELECT re.name, AVG(ra.rating) AS rating FROM resturants re LEFT JOIN ratings ra ON re.resturant_id = ra.resturant_id ORDER BY rating DESC LIMIT 5; I'm not sure if you can do an ORDER BY from an aggregate function. If you can this should give you what you want. Quote Link to comment https://forums.phpfreaks.com/topic/174706-solved-how-to-work-top-averages-out/#findComment-920737 Share on other sites More sharing options...
Andrew R Posted September 18, 2009 Author Share Posted September 18, 2009 Thanks a million! Quote Link to comment https://forums.phpfreaks.com/topic/174706-solved-how-to-work-top-averages-out/#findComment-920807 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.