簡體   English   中英

MySQL-從列中選擇隨機4個數據2個不同的唯一值

[英]MySql - select random 4 data 2 different unique values from a column

我正在嘗試從具有特定條件的t表中獲取4個數據的隨機數據集。

我嘗試選擇以下條件的4個數據

  1. 必須從數據集t表中隨機選擇f4 2個“ Y”和2個“ C”數據(可以是YYCCCYYCCCYY等)
  2. 在這4個數據中,只有一個與f2不同的數據集的唯一數據。

因此可以是ACFHADIHJHEC等。

到目前為止,我做到了這一點,但是在這4個數據上我無法獲得2'C'和2'Y'。

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'),
(9  ,'e'   ,'m'   ,'C'),
(10  ,'e'   ,'n'   ,'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 order by rand()
 LIMIT 4

結果

| f2 | f3 | f4 |
|----|----|----|
|  b |  r |  Y |
|  e |  n |  Y |
|  d |  o |  Y |
|  a |  w |  Y |

我期望的是;

| f2 | f3 | f4 |
|----|----|----|
|  b |  r |  Y |
|  e |  n |  C |
|  d |  o |  C |
|  a |  w |  Y |

使用UNION獲得兩個Y和兩個C

SELECT * FROM (
    SELECT f2, f3, f4
    FROM t
    WHERE f4 = 'Y'
    ORDER BY RAND()
    LIMIT 2) AS y
UNION ALL
SELECT * FROM(
    SELECT f2, f3, f4
    FROM t
    WHERE f4 = 'C'
    ORDER BY RAND()
    LIMIT 2) AS c

但是我不確定如何防止它們在兩個子查詢之間出現重復的f2值。

蠻力方法:

select t1.id as id1, t2.id as id2, t3.id as id3, t4.id as id4
from t t1
join t t2 on t2.f2 not in (t1.f2)
join t t3 on t3.f2 not in (t1.f2, t2.f2)
join t t4 on t4.f2 not in (t1.f2, t2.f2, t3.f2)
where t1.f4 = 'C'
  and t2.f4 = 'C'
  and t3.f4 = 'Y'
  and t4.f4 = 'Y'

演示: http//rextester.com/VNF93190

該查詢將返回所有可能的行ID組合。 在子查詢中選擇一個隨機組合,然后再次將其與表連接以獲取相應的行:

select t.*
from (
    select t1.id as id1, t2.id as id2, t3.id as id3, t4.id as id4
    from t t1
    join t t2 on t2.f2 not in (t1.f2)
    join t t3 on t3.f2 not in (t1.f2, t2.f2)
    join t t4 on t4.f2 not in (t1.f2, t2.f2, t3.f2)
    where t1.f4 = 'C'
      and t2.f4 = 'C'
      and t3.f4 = 'Y'
      and t4.f4 = 'Y'    
    order by rand()
    limit 1
) x
join t on t.id in (x.id1, x.id2, x.id3, x.id4)

演示: http//rextester.com/GQCCO60910

暫無
暫無

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

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