简体   繁体   English

MySQL-从一列中随机选择4个数据,以2个不同的列区分

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

I'm trying to select 4 different random data from a table on Mysql but I want some fields unique, for example; 我正在尝试从Mysql上的表中选择4种不同的随机数据,但是例如,我想要一些唯一的字段。

I've got a table 我有桌子

Table name 'videos' and the data is ; 表名“视频”,数据为;

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

I want to select 4 data randomly from f3 but f2 must be Unique. 我想从f3中随机选择4个数据,但f2必须是唯一的。 And the f4 must be unique for every f2, I mean I must get randomly 'u' or 'o' not both. 而且f4对于每个f2必须是唯一的,我的意思是我必须随机获得'u'或'o'而不是两者。 So in the end I want to get 2xC data column from unique f2, and 2xY data from unique f2. 所以最后我想从唯一的f2获取2xC数据列,并从唯一的f2获得2xY数据。 Result I want to get is like; 我想要得到的结果是;

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

Here's a sample that I created in MsSql but cant convert it to Mysql; 这是我在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

What about to sort randomly data then use mysql ONLY_FULL_GROUP_BY default behaviour ( disabled ): 如何随机排序数据然后使用mysql ONLY_FULL_GROUP_BY默认行为(禁用):

This causes MySQL to accept the preceding query. 这导致MySQL接受前面的查询。 In this case, the server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate, which is probably not what you want. 在这种情况下,服务器可以从每个组中自由选择任何值,因此,除非它们相同,否则选择的值是不确定的,这可能不是您想要的。 Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause. 此外,通过添加ORDER BY子句不会影响从每个组中选择值。

SQL Fiddle SQL小提琴

MySQL 5.6 Schema Setup : 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');

Query 1 : 查询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  

Results : 结果

| 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