How do I select random rows in MySQL?

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

    turbod was close with his answer, he was just ordering randomly, when it seems you wanted to order by pid, after getting the random rows you wanted in conjunction with the ones concerning A2 and A3:

    (
        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 `pid`
    

提交回复
热议问题