Home >Database >Mysql Tutorial >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:
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!