How do I select random rows in MySQL?

后端 未结 9 1135
慢半拍i
慢半拍i 2020-12-08 23:09
mytable

pid name field
=== ==== =====
1    A1   0
2    A2   1
3    A3   1
4    A4   0   
5    A5   0

This is my table structure. Here I want to se

相关标签:
9条回答
  • 2020-12-08 23:49

    Here is my solution:

    SELECT *
    FROM `mytable`
    WHERE name ='A2'
    OR name ='A3'
    LIMIT 2
    UNION
    (SELECT DISTINCT *
    FROM `mytable`
    WHERE name !='A2'
    OR name !='A3'
    ORDER BY RAND( ) LIMIT 2) ORDER BY RAND()
    
    0 讨论(0)
  • 2020-12-08 23:53

    Generally, using ORDER BY RAND() is not a good idea. Please read the text by Jan Kneschke, showing why: http://jan.kneschke.de/projects/mysql/order-by-rand/

    0 讨论(0)
  • 2020-12-08 23:54

    If you are always selecting all the rows in the table:

    SELECT pid, name, field, idx
    FROM (
        SELECT pid, name, field,
            @pos := IF(name = 'A3', @idx, @pos),
            @idx := @idx + IF(name = 'A3', 2, 1), idx
        FROM mytable, (SELECT @pos = -1, @idx := 0) dm
        WHERE name <> 'A2'
        ORDER BY RAND()
    )
    UNION SELECT pid, name, field, @pos + 1 idx
    FROM mytable
    WHERE name = 'A2'
    ORDER BY idx;
    

    If you are not always returning all the rows, thus need to check if A3 was returned to know if A2 should be included:

    SELECT pid, name, field, idx
    FROM (
        SELECT pid, name, field,
            @pos := IF(name = 'A3', @idx, @pos),
            @idx := @idx + IF(name = 'A3', 2, 1), idx
        FROM mytable, (SELECT @pos = -1, @idx := 0) dm
        WHERE name <> 'A2'
        ORDER BY RAND()
        LIMIT 4
    )
    UNION SELECT pid, name, field, @pos + 1 idx
    FROM mytable
    WHERE @pos != -1 AND name = 'A2'
    ORDER BY idx;
    
    0 讨论(0)
提交回复
热议问题