"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 Select the Top 3 Rows from Each Category in MySQL Without Analytic Functions?

How to Select the Top 3 Rows from Each Category in MySQL Without Analytic Functions?

Published on 2024-11-03
Browse:338

How to Select the Top 3 Rows from Each Category in MySQL Without Analytic Functions?

Selecting the Top 3 Rows from Multiple Categories in MySQL

Selecting the top rows from each category within a table can be challenging. One method utilizing views and subqueries, as outlined in the initial attempt, may return incorrect results.

A more effective approach employs analytic functions, which MySQL does not natively support. However, it's possible to emulate these functions using variables. Here's how:

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 

This query initializes variables @rownum and @category using a JOIN operation. It then assigns a rank to each row based on its category, incrementing the rank if the category changes.

Finally, the query selects only the rows with a rank of 3 or less. Note that you may need to modify the SELECT x.* clause to include only the desired columns.

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