J
J
jekahm2016-05-11 18:51:07
MySQL
jekahm, 2016-05-11 18:51:07

How to randomly select rows if there are duplicates in a certain field?

Good day!
Faced a problem of implementation of request of such sampling.
There is a table consisting of three fields ( id, header_id, user_id ). The value of the user_id field can be repeated multiple times. It is necessary to select rows within a certain range (i.e. ... WHERE user_id IN (...) ). In this case, if the value of user_id is repeated in the found rows, then one (row) of them must be randomly selected.
How can such a thing be implemented?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
guras256, 2016-05-11
@jekahm

SELECT 
  s.* 
FROM
  (SELECT
      t.id
      ,t.header_id
      ,t.user_id
  FROM
     test t
  WHERE
    t.user_id in (1,2,3,4,5)
  ORDER BY RAND()) s
GROUP BY s.user_id

I
inDeepCode, 2016-05-11
@inDeepCode

SELECT DISTINCT ...  GROUP BY('user_id') ORDER BY RAND();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question