Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I employ user variables to select x records for each value of a given column?
    primarykey
    data
    text
    <p><strong>EDIT: I've discovered this problem only appears when I use phpMyAdmin to execute the query, and not when I execute the same query using PHP's mysql_query(). (My webhost does not provide command-line access.) Specifically, when run on a table of 65k+ rows, phpMyAdmin appears to hang, but mysql_query() returns the expected result.</strong></p> <hr> <p>I have a table: products (product_id, shop_id, date)</p> <p>For each shop_id in the table, the following query retrieves the 10 rows with the most recent dates</p> <p><pre><code> set @num := 0, @shop_id := NULL;</p> <p>select shop_id, date from ( select shop_id, date, @num := if(@shop_id = shop_id, @num + 1, 1) as row_number, @shop_id := shop_id as dummy from products order by shop_id, date DESC ) as x where x.row_number &lt;= 10; </pre></code></p> <p>For example, if there are 10 distinct shop_ids, and each of these shop_ids appears in at least 10 rows, the query will return 100 rows, 10 per shop_id. This query works fine.</p> <p>In addition to the date and shop_id, I would also like to select the product_id for each row. However while the following query works fine up to abut 55k rows, when I try 65k rows, MySQL appears to hang indefinitely (at least the phpMyAdmin interface fails to return a page of results):</p> <p><pre><code> set @num := 0, @shop_id := NULL;</p> <p>select product_id, shop_id, date from ( select product_id, shop_id, date, @num := if(@shop_id = shop_id, @num + 1, 1) as row_number, @shop_id := shop_id as dummy from products order by shop_id, date DESC ) as x where row_number &lt;= 10; </pre></code></p> <p>I believe my tenuous grasp of user variables is to blame, but I cannot figure out what I am doing wrong.</p>
    singulars
    1. This table or related slice is empty.
    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. This table or related slice is empty.
    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