Home >Database >Mysql Tutorial >How to Return the Top 5 Items in Each Category in MySQL: Handling Subquery Errors?
How to Return the Top 5 Items in Each Category in MySQL
Returning a limited number of records from each category is a common requirement in database applications. In the specific case of returning the top 5 menu items per menu, the challenge arises due to the subquery returning multiple rows for each menu, leading to the "Subquery returns more than 1 row" error.
To overcome this issue, a common approach is to use side-effecting variables. Here's a corrected query that addresses the error:
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
Breaking down the query:
By utilizing side-effecting variables, this query ensures that it returns at most 5 records for each category, resolving the original error.
The above is the detailed content of How to Return the Top 5 Items in Each Category in MySQL: Handling Subquery Errors?. For more information, please follow other related articles on the PHP Chinese website!