"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Efficiently Select Top Rows per Category in MySQL Without Analytic Functions?

How to Efficiently Select Top Rows per Category in MySQL Without Analytic Functions?

Published on 2024-11-08
Browse:793

How to Efficiently Select Top Rows per Category in MySQL Without Analytic Functions?

Selecting Top Rows per Category in MySQL

To retrieve a limited number of rows from each category in a table, you can utilize analytic functions. However, MySQL doesn't offer these functions directly. Nevertheless, it's possible to emulate them using variables.

Emulating Analytic Functions

The following MySQL query emulates the functionality of analytic functions to select the top 3 rows for each category:

SELECT x.*
FROM (
    SELECT t.*,
    CASE 
        WHEN @category != t.category THEN @rownum := 1 
        ELSE @rownum := @rownum   1 
    END AS rank,
    @category := t.category AS var_category
    FROM TBL_ARTIKUJT t
    JOIN (SELECT @rownum := NULL, @category := '') r
    ORDER BY t.category
) x
WHERE x.rank 

Explanation

  • The subquery selects all rows from the TBL_ARTIKUJT table and initializes two session variables, @rownum and @category, to track the current ranking and category.
  • rank assigned to each row indicates its position within its category. When a new category is encountered, rank is reset to 1.
  • var_category is used to store the category for each row.
  • The outer SELECT statement filters the subquery, selecting only rows with a rank less than or equal to 3.

This method allows you to implement the desired functionality without relying on analytic functions, which are not supported by MySQL.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3