简体   繁体   中英

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;

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. And the f4 must be unique for every f2, I mean I must get randomly 'u' or 'o' not both. So in the end I want to get 2xC data column from unique f2, and 2xY data from unique f2. 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;

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

This causes MySQL to accept the preceding query. 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.

SQL Fiddle

MySQL 5.6 Schema Setup :

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 :

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 |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM