从大查询中的两个表中按 id 分组和按 id 随机抽样 sql

group by id and random sample by id from two tables in big query sql

我有 2 个 table 结构相同:

table1

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

table2

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

我想根据id从table1和table2中随机抽取数据。所以基本上,对来自 table1 的随机 id 样本的每个观察进行抽样,并对来自 table2 的 id 的随机样本进行每个观察,以便 50 个 id 来自 table 1 和 50 个是来自 table 2。关于如何在大查询上执行此操作的任何想法 SQL?

en 示例如下,我想从 table1 获取 3 个 ID,从 table2

获取 3 个 ID

随机 ID 1、2、3 select来自 table1,ID 101、110 和 103 select来自 table2

结果table是:

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

所以基本上所有来自 table1 的 id 为 1,2,3 的观察和来自 table2 的 id 为 101, 103, 110 的任何观察都是 selected 并放入同样的table: 所以段落是两个:首先随机 select 来自 table1 的一定数量的 id,以及来自 table2 的一定数量的 id,然后我 select 任何观察对应来自两个 table 的那些 ID,我将它们加入同一个 table

如果您希望每个 table 有 50 个 ID,那么您可以使用子查询来限制它们:

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