2

What Im Trying to achieve is selecting multiple rows randomly where a certain column is different from the last for example

SELECT * FROM mytable WHERE `column_for_duplicate_values` != '$thelastkey' ORDER BY RAND() LIMIT 10

the column for multiple values would hold for example:

1 , 1 , 1 , 1 , 2, 5 , 6, 6 , 6 , 6 , 6 , 11 , 11 ,  11 , 19

and I want to select 1 from each. So I would get

1 , 2 , 5 , 6 , 11 , 19
2
  • 1
    That is not random. That is distinct Commented Sep 15, 2015 at 16:03
  • But i want to select random rows theres around 95,000 records with these ID's Commented Sep 15, 2015 at 16:04

1 Answer 1

2

The main problem with my solution may be that it's

  1. slow
  2. not applicable

    You need to have a primary unique id in your mytable

      SELECT * FROM mytable WHERE id IN (
               SELECT id FROM (
                        SELECT id, column_for_duplicate_values 
                        FROM mytable ORDER BY RAND()) AS rand 
                        GROUP BY column_for_duplicate_values
                        ORDER BY RAND()) LIMIT 10;
    

The main concept is to first get a random list of all values with their id and the column you want to have unique values.

From this result we group by the value we only want to have once and only return the id. The main table will then select 10 random id's form this list.

I tried it with one of my db's. Should work with any table that has a unique id and some random other column.

If you append ORDER BY id ASC will also sort the id's.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this is perfect speed isnt a problem I have lots of processing power.
I updated the query and moved the limit to the end. The first version might output less than 10 distinct values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.