Search code examples
mysql

Select records randomly and different from previously selected records


I have a table with 8,000 rows, I want to randomly select some rows (for example 10) from this table. These rows have to be different from previously selected rows.

For example with this query I select some questions:

SELECT column1, column2 
FROM `myTable` 
WHERE `status` = 1 
  AND `group` = 6 
ORDER BY RAND() 
LIMIT 0, :max

Now how can I select new rows randomly and different from previously selected rows ?


Solution

  • Simply you could store the id's of previously selected rows and then add to your next query like below, to avoid selecting them twice:

    WHERE id NOT IN = (list of ids)
    

    Based on your example:

    SELECT column1, column2 
    FROM `myTable` 
    WHERE `status` = 1 
      AND `group` = 6 
      AND id NOT IN (_IDS_) 
    ORDER BY RAND() 
    LIMIT 0