Fetching rows in DB2

2020-05-23 13:59发布

I know in DB2 (using version 9.7) I can select the first 10 rows of a table by using this query:

SELECT * 
FROM myTable
ORDER BY id
FETCH FIRST 10 ROWS ONLY

But how can I get, for example, rows 11 to 20? I can't use the primary key or the ID to help me...

Thanks in advance!

标签: db2 fetch
2条回答
混吃等死
2楼-- · 2020-05-23 14:23

Here's a sample query that will get rows from a table contain state names, abbreviations, etc.

SELECT *
FROM (
   SELECT stabr, stname, ROW_NUMBER() OVER(ORDER BY stname) AS rownumber
   FROM states
   WHERE stcnab = 'US'
) AS xxx
WHERE rownumber BETWEEN 11 AND 20 ORDER BY stname

Edit: ORDER BY is necessary to guarantee that the row numbering is consistent between executions of the query.

查看更多
乱世女痞
3楼-- · 2020-05-23 14:25

You can also use the MYSQL compatibility. You just need to activate the vector compatibility for MYS, and then use Limit and Offset in your queries.

db2set DB2_COMPATIBILITY_VECTOR=MYS
db2stop
db2start
查看更多
登录 后发表回答