簡體   English   中英

MySQL-從一列中隨機選擇4個數據,以2個不同的列區分

[英]Mysql - select random 4 data from a column, distinct by 2 different columns

我正在嘗試從Mysql上的表中選擇4種不同的隨機數據,但是例如,我想要一些唯一的字段。

我有桌子

表名“視頻”,數據為;

id f2  f3  f4
-- --  --  --
1  a   q   C  
2  a   w   Y
3  b   e   C
4  b   r   Y
5  c   t   C
6  c   y   Y
7  d   u   C
8  d   o   Y

我想從f3中隨機選擇4個數據,但f2必須是唯一的。 而且f4對於每個f2必須是唯一的,我的意思是我必須隨機獲得'u'或'o'而不是兩者。 所以最后我想從唯一的f2獲取2xC數據列,並從唯一的f2獲得2xY數據。 我想要得到的結果是;

f3      f3        f3
--      --        --
q   or|  q   or|  w
r   or|  e   or|  r
t   or|  y   or|  t
o   or|  o   or|  u

這是我在MsSql中創建的示例,但是無法將其轉換為Mysql。

select e.* from (
      select top 4 f2,
             ROW_NUMBER() OVER (ORDER BY newId()) AS RowNumber 
      from (
         select distinct(f2) from videos
      ) x
) a inner join (
      select top 4 ones.n,
             ROW_NUMBER() OVER (ORDER BY newId()) AS RowNumber 
      FROM (VALUES('C'),('Y'),('C'),('Y')) ones(n)
) b on a.RowNumber = b.RowNumber
inner join videos e on a.f2 = e.f2 and b.n =e.f4

如何隨機排序數據然后使用mysql ONLY_FULL_GROUP_BY默認行為(禁用):

這導致MySQL接受前面的查詢。 在這種情況下,服務器可以從每個組中自由選擇任何值,因此,除非它們相同,否則選擇的值是不確定的,這可能不是您想要的。 此外,通過添加ORDER BY子句不會影響從每個組中選擇值。

SQL小提琴

MySQL 5.6模式設置

create table t ( id int, f2 char, f3 char, f4 char );
insert into t values
(1  ,'a'   ,'q'   ,'C'),
(2  ,'a'   ,'w'   ,'Y'),
(3  ,'b'   ,'e'   ,'C'),
(4  ,'b'   ,'r'   ,'Y'),
(5  ,'c'   ,'t'   ,'C'),
(6  ,'c'   ,'y'   ,'Y'),
(7  ,'d'   ,'u'   ,'C'),
(8  ,'d'   ,'o'   ,'Y');

查詢1

select  f2, f3, f4
from (
 select f2, f3, f4
 from (
  select f2, f4, f3 from
   ( select f2, f4, f3
     from t
     order by rand()
   ) t0
  group by f2
 ) t1  
 order by RAND() 
) t2
group by f2, f4  

結果

| f2 | f3 | f4 |
|----|----|----|
|  a |  w |  Y |
|  b |  r |  Y |
|  c |  t |  C |
|  d |  o |  Y |

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM