我需要从一张表中随机选择值,例如tableA.a_id
这是一个 VARCHAR2
,并使用该值插入到另一个表中。例如,假设需要将三列插入到 tableX
的 100 行中。 (一个序列号,一个 100 到 999 之间的随机数,以及 tableA.a_id
的值):
insert into tableX
select
rownum,
dbms_random.value(100,999), 0),
(select a_id from
(
SELECT a_id
FROM tableA
ORDER BY dbms_random.value
)
where rownum = 1)
from
(select level from dual connect by level <= 100);
但是,不是从
tableA.a_id
中随机选择一行对于每一行,它为所有行选择相同的值,例如:1 129 A-ID-48
2 849 A-ID-48
3 367 A-ID-48
但是,如果我重复执行子查询,我每次都会得到一个新值(出于显而易见的原因),例如:
select a_id from
(
SELECT a_id
FROM tableA
ORDER BY dbms_random.value
)
where rownum = 1;
结果将是每次执行后:
A-ID-7
A-ID-48
A-ID-74
我如何更改原始查询,或为此提出一个新查询,这将插入来自
tableA
的随机行的 a_id
目标表中每个插入行的列?想要的结果:1 129 A-ID-7
2 849 A-ID-48
3 367 A-ID-74
更新 1
基于 mathguy answer ,我更新了单个表选择的查询:
insert into tableX
select
rownum,
round(dbms_random.value(100,999), 0),
a_id
from
(
select
round(dbms_random.value(1, (select count(*) from tableA)), 0) tableX_rand_num
from tableX
) x
join
(
select
a_id,
dbms_random.value() rnd,
rownum tableA_rownum
from tableA
order by rnd
) a
on x.tableX_rand_num = a.tableA_rownum
where rownum <= 100;
限制 :使用此方法插入的行数不会独立于父表 (
tableX
) 中可用的记录数。换句话说,您只能插入与 tableX
中可用的总行数一样多的记录。 .例如如果 tableX
有 200 条记录,而您希望插入 1000 条,上面的查询只允许您插入最多 200 行。
最佳答案
进行内部查询:
select a_id, dbms_random.value() rnd from tableA order by rnd
然后在外部查询中一次性选择 100 行,使用
rownum <= 100
.像这样:
insert into tableX
select
rownum,
round(dbms_random.value(100,999), 0),
a_id
from
(
SELECT a_id, dbms_random.value() rnd
FROM tableA
ORDER BY rnd
)
where rownum <= 100;
关于sql - 在 Oracle 中选择随机行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39176498/