How to get random records from a pre-filtered list using MySQL subquery?
P粉776412597
P粉776412597 2024-04-02 09:44:53
0
1
440

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粉776412597
P粉776412597

reply all(1)
P粉863295057

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!