ORDER BY rand()和group with group_id

时间:2016-04-29 21:49:42

标签: php mysql sorting

我希望按group_id排序的随机顺序选择行:

id  group_id
1   1
2   1
3   2
4   2
5   3
6   4

我希望他们按照下面的方式排序或随机分组但仍然分组:

id  group_id
5   3
3   2
4   2
1   1
2   1
6   4

下面将对它们进行排序,但我希望这种排序是随机的。怎么做到这一点?

SELECT * FROM table ORDER BY group_id DESC

以下是我为实际应用确定的示例查询。

SELECT * FROM ( SELECT requests.*, accounts.username, accounts.password
FROM requests LEFT JOIN accounts ON requests.acc_id = accounts.id
WHERE requests.status NOT IN(1) AND accounts.status=1 ORDER BY RAND()
)  AS subquery GROUP BY acc_id 

3 个答案:

答案 0 :(得分:3)

您可以尝试使用随机数进行排序,其种子取决于group_id,但具有随机因子。 像这样:

SET @seed = 100*RAND();
SELECT * FROM table ORDER BY RAND(group_id*@seed);

答案 1 :(得分:0)

您可以使用随机排序所有组ID的子查询,并使用用户变量为其分配位置。然后将其与原始表格连接,并按位置进行排序。

SELECT t1.id, t1.group_id
FROM yourTable AS t1
JOIN (SELECT group_id, @position := @position + 1 as position
      FROM (SELECT DISTINCT(group_id) AS group_id
            FROM yourTable
            ORDER BY RAND()) AS x
      CROSS JOIN (SELECT @position := 0) AS var) AS t2
ON t1.group_id = t2.group_id
ORDER BY position, id

DEMO

答案 2 :(得分:0)

我不明白为什么其他答案和他们一样参与。

如果您需要按随机顺序排列的行,请执行ORDER BY RAND()

SELECT t.id
     , t.group_id
  FROM `table` t
 ORDER BY RAND()

请注意,RAND()不是真正随机的,它是 - 随机生成器。

我不明白你为什么需要内联视图。您可以在没有内联视图的情况下执行GROUP BY操作。给定GROUP BY,不需要在内联视图中执行不必要的ORDER BY操作。

 SELECT requests.*
      , accounts.username
      , accounts.password
   FROM requests
   LEFT
   JOIN accounts
     ON requests.acc_id = accounts.id
  WHERE requests.status NOT IN(1)
    AND accounts.status=1
  GROUP
     BY acc_id
  ORDER
     BY RAND()