Home >Database >Mysql Tutorial >How to Select the Top Two Articles from Each Category in MySQL?

How to Select the Top Two Articles from Each Category in MySQL?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-29 12:02:02633browse

How to Select the Top Two Articles from Each Category in MySQL?

MySQL Query: Selecting the Top Two Articles from Each Category

In MySQL, extracting a specified number of rows from a table is often achieved using the LIMIT clause. However, when the requirement is to select multiple rows based on grouping, a different approach is needed. This article addresses a specific scenario where two rows are to be selected from each category in a table.

Originally, the user attempted to achieve this by creating a view to limit rows and subsequently use a subquery to retrieve the desired records. However, this approach resulted in only two total records being returned.

The solution lies in utilizing what is commonly referred to as windowing functions. MySQL doesn't natively support windowing functions, but it's possible to emulate their functionality using user-defined variables as follows:

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;

In this revised query:

  • The outer query selects the columns from table TBL_ARTIKUJT (x.*).
  • The inner query, wrapped in parentheses, calculates the rank of each row within each category. It also defines two user-defined variables, @rownum and @category, which are used to track the current row number and category.
  • The WHERE clause filters the results to include only rows with a rank of 3 or less.

This approach effectively emulates windowing functions to group and select the desired rows from each category. If the intent is to retrieve only the original columns, the outer query can be modified to specify specific column names instead of x.*.

The above is the detailed content of How to Select the Top Two Articles from Each Category in MySQL?. 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