Home  >  Article  >  Database  >  How to Retrieve the Top 5 Items from Each Category in MySQL While Avoiding the "Subquery Returns More Than 1 Row" Error?

How to Retrieve the Top 5 Items from Each Category in MySQL While Avoiding the "Subquery Returns More Than 1 Row" Error?

Linda Hamilton
Linda HamiltonOriginal
2024-11-10 09:13:03480browse

How to Retrieve the Top 5 Items from Each Category in MySQL While Avoiding the

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.

  1. @g:=null - Initializes @g to NULL, indicating that we are starting a new group.
  2. @r:=0 - Initializes @r to 0, signifying the beginning of a new rank.
  3. The WHERE clause in the subquery (where m.menuid = s.menuid) ensures that s and m are aligned based on menu ID.
  4. @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.
  5. @g:=m.profilename - Updates @g with the current group's profile name, allowing us to track subsequent rows belonging to this group.
  6. The main query retrieves the profilename and name from the subquery table alias X.
  7. 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