mysql-从列中随机选择4个数据和2个不同的唯一值

vh0rcniy  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(345)

我试着在特定条件下从t表中获得一个包含4个数据的随机数据集。
我试着选择4个条件如下的数据
中必须有2个“y”和2个“c”数据 f4 从数据集t表中随机选择(可以 Y-Y-C-C 或者 C-Y-Y-C 或者 C-C-Y-Y 等)
数据集distinct只能有一个唯一的数据 f2 在那4个数据里。
所以可以 A-C-F-H 或者 A-D-I-H 或者 J-H-E-C 等。
到目前为止,我做了这个,但是我不能得到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 |
x6492ojm

x6492ojm1#

使用 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 两个子查询之间的值。

jckbn6z7

jckbn6z72#

暴力方法:

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

相关问题