简体   繁体   中英

Oracle 11g: union all with dbms_random

I'm trying to write sql statement in oracle 11g that will randomly select 5000 records from union of two different tables with same columns:

select * 
  from (
       select ename, job
       from emp1
       union all
       select ename, job
       from emp2
       order by dbms_random.value()
        )
where rownum <= 5000

And when run it, I get error ORA-01785: ORDER BY item must be the number of a SELECT-list expression. When I remove second table it works just fine. But, now I need to select randomly from two tables, first union all them, order them randomly and then select 5000 of them.

Or maybe there is some other approach with same result?

Tnx for help.

Your ORDER BY applies only to the second part of the UNION ALL - you'll have to perform the UNION ALL first and then apply the ORDER BY:

select * 
  from (
    select * from (
       select ename, job
       from emp1
       union all
       select ename, job
       from emp2
    )
    order by dbms_random.value()
)
where rownum <= 5000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM