Home > Database > Mysql Tutorial > body text

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

Patricia Arquette
Release: 2024-10-27 23:23:30
Original
544 people have browsed it

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:

<code class="sql">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 <= 3;</code>
Copy after login

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.

The above is the detailed content of How to Select the Top 3 Rows from Each Category in MySQL Without Analytic Functions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!