问题
I have a table -
emp_record
which has 40,000 records And I want to fetch the records from java code and below is the requirement -
- At a time only 1000 records should be returned
- In the next hit next 1000 records
- continue till all the records exhaust
- The SQL query should not be nested, like
select *
from(
SELECT a.*,rownum rn
FROM distributor a)
WHERE rn >= 3000 and rn < 4000;
Any sort of help is much appreciated.
回答1:
This sounds very artifical as 40.000 records is nothing. I would just read them in one query and perhaps hand them out in batches. In that case you can use statement.setFetchSize(1000)
to make the JDBC driver fetch 1000 records at a time and position that as solving the requirement.
Alternatively if you are on Oracle 12 you can use:
select * from distributor
order by something_unique
offset x rows fetch next 1000 rows only
where x is the starting position. It does the same thing as the rownum construction, but with a much nicer syntax.
回答2:
You could use a query that uses ROWNUM
by first ordering the rows by a primary key/unique key. Idea from the query here : Best practice for pagination in Oracle?
SELECT *
FROM (SELECT A.*, rownum rn
FROM (SELECT *
FROM emp_record
ORDER BY pri_key_col) A
WHERE rownum <= :n * 1000)
WHERE rn > (:n - 1) * 1000;
pri_key_col
: Primary key/ unique key column of your table.n
: number indicating the batch. If n = 1, it returns first 1000 records ordered that way, n=2 gives next 1000 and so on.
来源:https://stackoverflow.com/questions/50562167/how-to-fetch-data-from-oracle-in-batches-from-java-in-equal-batches