将Postgres SQL查询转换为Oracle

时间:2019-04-11 12:33:19

标签: sql oracle postgresql

我正在尝试加快Oracle中的随机选择查询的速度,并找到了这个blog。我无法在oracle中转换其以下Postgres查询:

    select * from users
      where 
        random() < 200 / (select count(1) from logs)::float
      order by random()
      limit 100;

   select * from users
     where id in (
       select round(random() * 21e6)::integer as id
       from generate_series(1, 110)
       group by id -- Discard duplicates
       )
     limit 100;

此查询在oracle中的外观如何?

1 个答案:

答案 0 :(得分:1)

您可以使用此类查询:

 select * from 
 (
 select u.*, row_number() over (order by dbms_random.value) as rn 
   from users u
  where 
    dbms_random.value < 200 / (select count(1) from logs)
  )
  where rn <= 100;

select * from
(
select u.*, row_number() over (order by 1) as rn
  from users u
 where id in (
              select round(dbms_random.value * 21e6) as id                    
                from dual
             connect by level <= 110  
             )
 )
 where rn <= 100;

如果您的Oracle DB版本为12c,则可以在子查询中用where rn <= 100替换fetch first 100 rows only部分,并删除rn(由row_number()函数组成)列。