Retrieving the Top 5 Items from Each Category in MySQL
Encountering the error "Subquery returns more than 1 row" while trying to fetch the top five menu items for each menu category? The solution resides in employing side effecting variables.
Let's break down the revised approach:
In the subquery, we introduce side effecting variables @r and @g using SQL's @ notation. These variables are used to track group membership and increment the rank within each group.
- @g:=null - Initializes @g to NULL, indicating that we are starting a new group.
- @r:=0 - Initializes @r to 0, signifying the beginning of a new rank.
- The WHERE clause in the subquery (where m.menuid = s.menuid) ensures that s and m are aligned based on menu ID.
- @r:=case when @g=m.profilename then @r 1 else 1 end - This case expression increments @r by 1 if m.profilename is the same as the current group (@g). Otherwise, it resets @r to 1, signaling the start of a new group.
- @g:=m.profilename - Updates @g with the current group's profile name, allowing us to track subsequent rows belonging to this group.
- The main query retrieves the profilename and name from the subquery table alias X.
- The final WHERE r <= 5 condition filters out only the top 5 ranked items within each group.
By implementing this approach, you can efficiently obtain the desired results without the "Subquery returns more than 1 row" error.
The above is the detailed content of How to Retrieve the Top 5 Items from Each Category in MySQL While Avoiding the "Subquery Returns More Than 1 Row" Error?. For more information, please follow other related articles on the PHP Chinese website!
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn