大查询sql中两个表的group by id和random sample by id

x3naxklr  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(274)

我有两张结构相同的table:
表1

id text        var  
1  "bla bla"   100
1  "blabla1"    30
2  "qweweqty"    0
2    etc...
7
3
3
1
..
100

表2

id text        var  
101 "bla bla"   10
101  "bla1"      60
101  "bla"    5
103    etc...
102
103
102
110
..
200

我想根据id从表1和表2中随机抽取数据。所以基本上,从表1中随机抽取一个id,从表2中随机抽取一个id,从表1中随机抽取50个id,从表2中随机抽取50个id。你知道如何在大查询sql上做到这一点吗?
例如,我想从表1中得到3个ID,从表2中得到3个ID
从表1中随机选择ID 1、2、3,从表2中随机选择ID 101、110和103
结果表如下:

id. text var
 1.   ..  ..
 1
 2
 2
 3
 3
 1
 101
 101
 101
 103
 103
 110

因此,基本上,表1中id为1、2、3的任何观察和表2中id为101、103、110的任何观察都被选择并放在同一个表中:因此段落有两个:首先从表1中随机选择一定数量的id,然后从表2中随机选择一定数量的id,然后我从两个表中选择与这些id相对应的任何观察,并将它们连接到同一个表中

ulmd4ohb

ulmd4ohb1#

如果希望每个表中有50个ID,则可以使用子查询对其进行限制:

select t1.*
from t1 join
     (select distinct id
      from t1
      order by rand()
     ) ids
     on t1.id = ids.id
union all
select t2.* 
from t2 join
     (select distinct id
      from t2
      order by rand()
     ) ids
     on t2.id = ids.id

相关问题