Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is the greatest-n-per-group problem, and it's a very common SQL question.</p> <p>Here's how I solve it with outer joins:</p> <pre><code>SELECT i1.* FROM item i1 LEFT OUTER JOIN item i2 ON (i1.category_id = i2.category_id AND i1.item_id &lt; i2.item_id) GROUP BY i1.item_id HAVING COUNT(*) &lt; 4 ORDER BY category_id, date_listed; </code></pre> <p>I'm assuming the primary key of the <code>item</code> table is <code>item_id</code>, and that it's a monotonically increasing pseudokey. That is, a greater value in <code>item_id</code> corresponds to a newer row in <code>item</code>.</p> <p>Here's how it works: for each item, there are some number of other items that are newer. For example, there are three items newer than the fourth newest item. There are zero items newer than the very newest item. So we want to compare each item (<code>i1</code>) to the set of items (<code>i2</code>) that are newer and have the same category as <code>i1</code>. If the number of those newer items is less than four, <code>i1</code> is one of those we include. Otherwise, don't include it.</p> <p>The beauty of this solution is that it works no matter how many categories you have, and continues working if you change the categories. It also works even if the number of items in some categories is fewer than four.</p> <hr> <p>Another solution that works but relies on the MySQL user-variables feature:</p> <pre><code>SELECT * FROM ( SELECT i.*, @r := IF(@g = category_id, @r+1, 1) AS rownum, @g := category_id FROM (@g:=null, @r:=0) AS _init CROSS JOIN item i ORDER BY i.category_id, i.date_listed ) AS t WHERE t.rownum &lt;= 3; </code></pre> <hr> <p>MySQL 8.0.3 introduced support for SQL standard window functions. Now we can solve this sort of problem the way other RDBMS do:</p> <pre><code>WITH numbered_item AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY item_id) AS rownum FROM item ) SELECT * FROM numbered_item WHERE rownum &lt;= 4; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload