mysql 分组依据值兰德()

yxyvkwin  于 2023-01-08  发布在  Mysql
关注(0)|答案(6)|浏览(140)

有可能通过下式得到一个随机值?

----------------
 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

但我希望每个人都有不同的结果,比如:

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

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

有可能吗?
http://sqlfiddle.com/#!2/357b8/3

xnifntxz

xnifntxz1#

使用子查询。

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

vfh0ocws

vfh0ocws2#

您可以使用兰德()排序,然后按它们分组。
喜欢

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

zzlelutf3#

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 ;
jmp7cifd

jmp7cifd4#

试试这个

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

lyfkaqu15#

下面的解决方案在本质上与xdazzjonnyynnoj中的解决方案类似,但我使用子查询来选择所有不同的ID,而不是SELECT FROM T1 GROUP BY nID。我相信性能可能会有所不同,所以给予这个解决方案。

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
jckbn6z7

jckbn6z76#

兰德+行编号

SELECT t.*
, @rownum := @rownum+1 AS rowNum
FROM(
  SELECT nID, VAL 
  FROM T1 
  ORDER BY RAND()
) AS t, (SELECT @rownum :=0) AS R
GROUP BY nID
ORDER BY nID, rowNum

相关问题