How do I select a fixed number of rows for each group?

后端 未结 3 1422
[愿得一人]
[愿得一人] 2020-12-31 17:10

Here is some example data in a mysql table

a   b   distance
15  44  250
94  31  250
30  41  250
6   1   250
95  18  250
72  84  500
14  23  500
55  24  500
9         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-31 18:12

    One way would be to use union. Like so:

    (SELECT a, b, distance FROM table WHERE distance = 250 LIMIT 2 ORDER BY RAND())
    UNION
    (SELECT a, b, distance FROM table WHERE distance = 500 LIMIT 2 ORDER BY RAND())
    ...
    ORDER BY distance
    

    I can think of a way of getting one of each with one query using distinct =/, but like I said that would only bring you one.

提交回复
热议问题