Home > Article > Backend Development > php mssql database paging SQL statement_PHP tutorial
When we write systems such as MIS systems and Web applications, they all involve interaction with the database. If the amount of data in the database is large, retrieving all records at once will occupy a lot of system resources. Therefore, we often use Only fetch as many records from the database as there is data, that is, use paging statements. Based on the content I have used, the paging statements of common databases Sql Server, Oracle and MySQL, and the statements that start from the Mth data in the database table to fetch N records are summarized as follows:
SQL Server
Fetch N records starting from the Mth record in the database table, using the Top keyword: Note that if there is both top and order by in the Select statement, it will be selected from the sorted result set:
SELECT *
FROM (SELECT Top N *
FROM (SELECT Top (M + N - 1) * FROM table name Order by primary key desc) t1 ) t2
Order by primary key asc
Example:
select * from ( select TOP pagesize * FROM ( SELECT TOP pagesize*cureentpage * from user_table ORDER BY id ASC ) as aSysTable ORDER BY id DESC ) as bSysTable ORDER BY id ASC
For example, from table Sys_option (primary key is sys_id) To retrieve 20 records from 10 records, the statement is as follows:
SELECT *
FROM ( SELECT TOP 20 *
FROM (SELECT TOP 29 * FROM Sys_option order by sys_id desc) t1) t2
Order by sys_id asc
Oralce database
Retrieve N records starting from the M record in the database table
SELECT *
FROM (SELECT ROWNUM r,t1.* From table Name t1 where rownum < M + N) t2
where t2.r >= M
For example, whether to retrieve 10 records or 20 records from the table Sys_option (the primary key is sys_id), the statement is as follows:
SELECT *
FROM (SELECT ROWNUM R,t1.* From Sys_option where rownum < 30 ) t2
Where t2.R >= 10
MySQL database
My The simplest SQL database is to use the LIMIT function of mysql. LIMIT [offset,] rows The statement to retrieve N records starting from M records in the database table is:
SELECT * FROM table name LIMIT M,N
For example To retrieve 10 or 20 records from the table Sys_option (the primary key is sys_id), the statement is as follows:
Select * from sys_option limit 10,20