Group By value RAND()

后端 未结 5 1252
星月不相逢
星月不相逢 2021-01-04 10:49

It\'s possible get a random value of the group by?

----------------
 nID |  val
---------------
  A  |   XXX
  A  |   YYY
  B  |   L
  B  |   M
  B  |   N
           


        
相关标签:
5条回答
  • 2021-01-04 11:08

    Try This

    SELECT nID, VAL
    FROM (select nID, VAL from T1 order by rand()) as T
    group by nID
    
    0 讨论(0)
  • 2021-01-04 11:09

    You can use order by rand() then group by them.

    Like

      SELECT nID, VAL FROM (
      SELECT nID, VAL
      FROM T1
      ORDER BY RAND()
      )AS subquery
    GROUP BY nID
    
    0 讨论(0)
  • 2021-01-04 11:13

    The following solution is similar in spirit to those from xdazz or jonnyynnoj. But instead of SELECT FROM T1 GROUP BY nID I use a subquery to select all distinct IDs. I believe there is a chance that the performance might differ, so give this one a try as well.

    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
    
    0 讨论(0)
  • 2021-01-04 11:15

    Use a sub-query.

    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

    0 讨论(0)
  • 2021-01-04 11:32
    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 ; 
    
    0 讨论(0)
提交回复
热议问题