sql - 在 Oracle 中选择随机行

标签 sql oracle random insertion

我需要从一张表中随机选择值,例如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/

相关文章:

c# - 无法将类型 'int' 隐式转换为 'System.Data.DataTable'

mysql - 如果使用 MySQL 存在行,则获取列?

sql - Oracle 中的 Case 语句显示所有内容而不是查询项

c# - 异步 I/O 密集型代码比非异步代码运行速度慢,为什么?

sql - 如何修复 Oracle 中 SQL 中的 "ORA-01801: date format is too long for internal buffer"错误

php - 选择更好的结果匹配

sql - 如何从 sp_msforeachtable 中排除表

java - 我应该使用 java.util.Random 的全局实例,还是每次使用它时都构造一个?

mysql - 使用随机唯一数字更新 SQL 表

c# - 如何确定文件名是否随机?