Returning the Top 5 Items from Each Category in MySQL
Challenge:
Retrieving the top 5 menu items from each category in a database consisting of two tables, "menus" and "menuitems."
Solution:
The presented code aims to display the top 5 items per menu category. However, it returns with an error due to the subquery retrieving multiple rows. To address this, side effecting variables can be utilized to track the position of each row within the category.
SELECT profilename, name FROM ( SELECT m.profilename, s.name, @r:=case when @g=m.profilename then @r+1 else 1 end r, @g:=m.profilename FROM (select @g:=null,@r:=0) n cross join menus m left join menuitems s on m.menuid = s.menuid ) X WHERE r <= 5
Breakdown:
The above is the detailed content of How to Retrieve the Top 5 Menu Items from Each Category in MySQL?. For more information, please follow other related articles on the PHP Chinese website!