Home  >  Q&A  >  body text

How to get random records from a pre-filtered list using MySQL subquery?

I searched but couldn't find a working solution. Need a little help here.

Suppose I have a table with more than 100 records. First, I need to find the first 20 records in a certain order, and then I need to randomly pick 5 records from these 20 records. This is my query,

SELECT a 
FROM tableA 
WHERE b IN (
    SELECT b 
    FROM tableA 
    WHERE c="x" 
    ORDER BY d DESC 
    LIMIT 20
) 
ORDER BY RAND() 
LIMIT 5;

Let me know how to correct it. Thanks.

P粉776412597P粉776412597186 days ago442

reply all(1)I'll reply

  • P粉863295057

    P粉8632950572024-04-03 00:11:25

    The inner query selects 20 users sorted by ID, the outer query uses the RAND() function to randomly order, with a limit of 5 :)

    SELECT * FROM 
    (
        SELECT * FROM A ORDER BY id desc LIMIT 20
    ) T1
    ORDER BY rand() limit 5

    reply
    0
  • Cancelreply