sql语法中的一个重点
count(*) 比count(id)好
select count(DISTINCT t_enter,caller) as size from tab可以踢出重复统计
mysql可以断章取义(从0开始10个)
select * as size from tab limit 0,10
也可以取前几个
select * as size from tab limit 10
就等价与mssql的top
select top 10 * as size from tab
mssqlserver要实现limit的选取功能就比较麻烦比如从4~6可以如下写法:
select * from (select top 3 * from (select top 6 * from @t order by id)a order by a.id desc)b order by b.id
===============================================以下是抄来的
http://www.west263.com/www/info/34371-1.htm
create table [testtable] (
[id] [int] identity (1, 1) not null ,
[firstname] [nvarchar] (100) collate chinese_prc_ci_as null ,
[lastname] [nvarchar] (100) collate chinese_prc_ci_as null ,
[country] [nvarchar] (50) collate chinese_prc_ci_as null ,
[note] [nvarchar] (2000) collate chinese_prc_ci_as null
) on [primary]
go
插入数据:(2万条,用更多的数据测试会明显一些)
set identity_insert testtable on
declare @i int
set @i=1
while @i<=20000
begin
insert into testtable([id], firstname, lastname, country,note) values(@i, firstname_xxx,lastname_xxx,country_xxx,note_xxx)
set @i=@i+1
end
set identity_insert testtable off
-------------------------------------
分页方案一:(利用not in和select top分页)
语句形式:
select top 10 *
from testtable
where (id not in
(select top 20 id
from testtable
order by id))
order by id
select top 页大小 *
from testtable
where (id not in
(select top 页大小*页数 id
from 表
order by id))
order by id
-------------------------------------
分页方案二:(利用id大于多少和select top分页)
语句形式:
select top 10 *
from testtable
where (id >
(select max(id)
from (select top 20 id
from testtable
order by id) as t))
order by id
select top 页大小 *
from testtable
where (id >
(select max(id)
from (select top 页大小*页数 id
from 表
order by id) as t))
order by id
-------------------------------------
分页方案三:(利用sql的游标存储过程分页)
create procedure xiaozhengge
@sqlstr nvarchar(4000), --查询字符串
@currentpage int, --第n页
@pagesize int --每页行数
as
set nocount on
declare @p1 int, --p1是游标的id
@rowcount int
exec sp_cursoropen @p1 output,@sqlstr,@scrollopt=1,@ccopt=1,@rowcount=@rowcount output
select ceiling(1.0*@rowcount/@pagesize) as 总页数--,@rowcount as 总行数,@currentpage as 当前页
set @currentpage=(@currentpage-1)*@pagesize+1
exec sp_cursorfetch @p1,16,@currentpage,@pagesize
exec sp_cursorclose @p1
set nocount off
其它的方案:如果没有主键,可以用临时表,也可以用方案三做,但是效率会低。
建议优化的时候,加上主键和索引,查询效率会提高。
通过sql 查询分析器,显示比较:我的结论是:
分页方案二:(利用id大于多少和select top分页)效率最高,需要拼接sql语句
分页方案一:(利用not in和select top分页) 效率次之,需要拼接sql语句
分页方案三:(利用sql的游标存储过程分页) 效率最差,但是最为通用
在实际情况中,要具体分析。