A-A+

数据库读取中间几条记录的SQL语句

2012年05月21日 PHP技术文章 暂无评论 阅读 469 views 次

在编程中,经常会用到取数据库中某一段的记录,如果要取前几条记录都是很简单,在asp中,直接用top就可以了,在php中,用limit就可以,但如果要取数据库中的第 N 条到第 N条怎么办呢,也就是要取数据库中间的数据,在php,取中间的数据,可以用 limit 很自然的就实现了,主要是asp编程中,需要在sql语句中再重新嵌入一个 sql语句,下面看看 asp 和 php 中不同的 sql 读取中间几条记录。

1 Access 采用top

从表中取出第 M 条到第 N 条的记录(如N=M+10)

select top N-M+1 * from [tableName] where (id not in (select top M-1 id from [tableName]))
select top N-M+1 * from [tableName] as a where not exists (select * from (select top M-1 * from [tableName] order by id) b where b.id=a.id ) order by id

注意:上述语句不能取从第1条到第N条的数据(即M=1时失效),因为select top N …… 中N必须从1开始(参考:数据库读取前几条记录的SQL语句大全):此问题的解决办法:要取第1到N条的记录,需要使用select top N …… 解决。

取数据库第20到第30条中间的十条记录的sql语句
select top 10 * from [tableName] where id not in (select top 20 id from [tableName] order by id)

删除前10行
delete from [tableName] where id in(select top 10 id from [tableName])

删除10-20条
delete from [tableName] where id in(select top 20 id from [tableName]) and id not in(select top 10 id from [tableName])

2 MySql 采用limit

limit 子句可以被用于强制 select 语句返回指定的记录数。limit 接受一个或两个数字参数。参数必须是一个整数常量。如果给定两个参数,第一个参数指定第一个返回记录行的偏移量,第二个参数指定返回记录行的最大数目。初始记录行的偏移量是 0(而不是 1)

检索记录行11-15
select * from [tableName] limit 10,15

标签:

给我留言