8

这是mysql表中的一些示例数据

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
95  8   500
59  25  500
40  73  500
65  85  500
32  50  500
31  39  500
22  25  500
37  11  750
98  39  750
15  57  750
9   22  750
14  44  750
69  22  750
62  50  750
89  35  750
67  65  750
74  37  750
52  36  750
66  53  750
82  74  1000
79  22  1000
98  41  1000

如何查询此表,以便随机选择每个距离 2 行?

一个成功的查询会产生类似

   a    b   distance
    30  41  250
    95  18  250
    59  25  500
    65  85  500
    15  57  750
    89  35  750
    79  22  1000
    98  41  1000
4

3 回答 3

7

采用:

SELECT x.a,
       x.b,
       x.distance
  FROM (SELECT t.a,
               t.b,
               t.distance
               CASE 
                 WHEN @distance != t.distance THEN @rownum := 1 
                 ELSE @rownum := @rownum + 1 
               END AS rank,
               @distance := t.distance
          FROM TABLE t
          JOIN (SELECT @rownum := 0, @distance := '') r
      ORDER BY t.distance --important for resetting the rownum variable) x
 WHERE x.rank <= 2
ORDER BY x.distance, x.a
于 2010-05-21T22:51:38.333 回答
0

一种方法是使用联合。像这样:

(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

我可以想到一种方法,使用 distinct =/ 获得一个查询,但就像我说的那样,这只会给你带来一个。

于 2010-05-21T22:53:26.210 回答
0

我想知道这是否可行?

SELECT 
   a,b,distance 
FROM YourTable t2
   WHERE ROW(a,b,distance) IN 
   (
      SELECT a,b,distance FROM YourTable t1 
      WHERE t1.distance=t2.distance ORDER BY RAND() LIMIT 2
   )

编辑:不幸的是没有。子查询不支持 LIMIT。

于 2010-05-21T23:08:02.560 回答