How do I select random rows in MySQL?

后端 未结 9 1138
慢半拍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:40

    I ran a heavy test on this, passed.

    (
    SELECT * , 0.5 AS ordercol
    FROM `mytable`
    WHERE `name`IN ( "A2", "A3" )
    LIMIT 2
    )
    UNION (
    SELECT * , rand() AS ordercol
    FROM `mytable`
    WHERE `name` NOT IN ( "A2", "A3" )
    LIMIT 2
    )
    ORDER BY ordercol, `name` IN ( "A2", "A3" ) , `name` ="A3"
    

    This will do the job very well. But to make the result even more random, execute that statement with replacing that 0.5 value in 1st line with a random value chosen by your client application code like mt_rand(0, 1000000) / 1000000 in PHP . Make sure it falls between 0 and 1. But do NOT use mysql function rand() in place of that 0.5 because it will make A2 and A3 apart from each other. The trick is assigning a random value for "ordercol" in all rows but keep it same for A2 and A3

    EDIT: I believe we can replace the 0.5 value with a LEFT JOIN even instead of relying on discrete value by PHP, as we replace the first segment of the union, so the whole query becomes:

    (
    SELECT mt1.* , mt2.ordercol AS ordercol
    FROM `mytable` AS mt1
    LEFT JOIN (
    
    SELECT RAND( ) AS ordercol
    ) AS mt2 ON TRUE
    WHERE `name`
    IN (
    "A2", "A3"
    )
    LIMIT 2
    )
    UNION (
    SELECT * , rand() AS ordercol
    FROM `mytable`
    WHERE `name` NOT IN ( "A2", "A3" )
    LIMIT 2
    )
    ORDER BY ordercol, `name` IN ( "A2", "A3" ) , `name` ="A3"
    

提交回复
热议问题