分组值RAND()

时间:2012-10-04 10:33:23

标签: mysql sql group-by

可以通过?

得到该组的随机值
----------------
 nID |  val
---------------
  A  |   XXX
  A  |   YYY
  B  |   L
  B  |   M
  B  |   N
  B  |   P
----------------

使用此SQL:

SELECT nID, VAL FROM T1 GROUP BY nID

我的结果总是:

nID  val
--------
A    XXX
B    L

但我想要一个不同的evey nID结果。像:

nID  val
--------
A    YYY
B    N

nID  val
--------
A    XXX
B    P

有可能吗?

http://sqlfiddle.com/#!2/357b8/3

5 个答案:

答案 0 :(得分:3)

您可以按rand()使用订单 然后由他们分组。

  SELECT nID, VAL FROM (
  SELECT nID, VAL
  FROM T1
  ORDER BY RAND()
  )AS subquery
GROUP BY nID

答案 1 :(得分:2)

使用子查询。

SELECT r.nID,
(SELECT r1.val FROM T1 r1 WHERE r.nID=r1.nID ORDER BY rand() LIMIT 1) AS 'val' FROM T1 r 
GROUP BY r.nID

http://sqlfiddle.com/#!2/357b8/18

答案 2 :(得分:1)

SELECT 
  t1.nID, 
  (SELECT 
     t2.var 
   FROM your_table t2 
   WHERE t1.nID = t2.nID ORDER BY rand() LIMIT 1
  ) AS var 
FROM your_table t1 
GROUP BY t1.nID ; 

答案 3 :(得分:0)

试试这个

SELECT nID, VAL
FROM (select nID, VAL from T1 order by rand()) as T
group by nID

答案 4 :(得分:0)

以下解决方案在精神上类似于xdazzjonnyynnoj的解决方案。但我使用子查询代替SELECT FROM T1 GROUP BY nID来选择所有不同的ID。我相信表演可能会有所不同,所以也要尝试一下。

SELECT nID,
  (SELECT VAL
   FROM T1
   WHERE T1.nID = ids.nID
   ORDER BY RAND()
   LIMIT 1
  ) AS VAL
FROM (SELECT DISTINCT nID FROM T1) AS ids