Select the latest items in each category using a single query
In a database of items classified by a field named category_id
, the task is to retrieve a list of categories, each containing its four most recently listed items. Rather than querying the database individually for each category, use a single SQL query to optimize the database calls.
Solution using outer join:
The following query uses an outer join to identify and exclude items that have updated counterparts in the same category:
<code class="language-sql">SELECT i1.* FROM item i1 LEFT OUTER JOIN item i2 ON (i1.category_id = i2.category_id AND i1.item_id < i2.item_id) GROUP BY i1.category_id, i1.item_id HAVING COUNT(*) <= 4;</code>
This query uses LEFT OUTER JOIN
to join each item (i1
) with its updated set of items (i2
) that has the same category. COUNT(*)
Used to count the number of matches for each item in each category. The HAVING
clause filters out items with more than four matches, ensuring that only the four newest items in each category are selected.
Solution using MySQL user variables:
This solution utilizes MySQL's user variable feature to track group and row numbers:
<code class="language-sql">SELECT * FROM ( SELECT i.*, @r := IF(@g = category_id, @r+1, 1) AS rownum, @g := category_id FROM (SELECT @g:=null, @r:=0) AS _init CROSS JOIN item i ORDER BY i.category_id, date_listed DESC ) AS t WHERE t.rownum <= 4;</code>
In this query, the user-defined variables @g
and @r
are used to keep track of the current category and row number, ensuring that only the first four items in each category are selected.
Solution using MySQL window functions (MySQL 8.0.3):
MySQL 8.0.3 introduces support for SQL standard window functions, providing a more concise and efficient solution:
<code class="language-sql">WITH numbered_item AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY date_listed DESC) AS rownum FROM item ) SELECT * FROM numbered_item WHERE rownum <= 4;</code>
This query uses the PARTITION BY category_id ORDER BY date_listed DESC
clause to partition the result set by category and sort the items in descending order by the date_listed
column in each partition. The ROW_NUMBER()
window function then assigns consecutive row numbers to each partition, enabling the selection of the first four items of each category.
The above is the detailed content of How to Retrieve the Four Newest Items Per Category with a Single SQL Query?. For more information, please follow other related articles on the PHP Chinese website!