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:
<code class="mysql">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>
Explanation
This method allows you to implement the desired functionality without relying on analytic functions, which are not supported by MySQL.
The above is the detailed content of How to Efficiently Select Top Rows per Category in MySQL Without Analytic Functions?. For more information, please follow other related articles on the PHP Chinese website!