mardi 26 décembre 2017

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




Aucun commentaire:

Enregistrer un commentaire