表的结构非常简单,只有两列,ID跟CID,示例数据如下:
ID CID
----------- -----------
0 1
0 2
0 3
1 1
1 2
1 3
2 2
2 3
3 1
3 2
3 3
4 1
4 2
4 3
5 1
5 3
6 1
6 2
我现在要查询的是CID的值中含有1和2的ID,如上面的数据中查询出来的结果应该是:
0、1、3、4、6
且要分页查询。
测试表及数据SQL:
--create test table
create table TestA(
ID int not null,
CID int not null,
Primary Key(ID,CID)
);
GO
--insert into test data
declare @count int
set @count=0
while @count<50000
begin
if @count<40000
begin
insert into TestA values (@count,1);
insert into TestA values (@count,2);
insert into TestA values (@count,3);
end
else
insert into TestA values (@count,2);
set @count=@count+1;
end
Go
测试数据有13万,例如每页30条数据,查询第1334页,我的SQL语句及结果如下:
-- my method
set statistics io on
select top 30 ID from TestA
where (CID =1 or CID =2) and ID >(SELECT MAX(ID) FROM (select top (1333*30) id from TestA where CID=1 or CID=2 group by ID having count(ID)>1 order by ID)a)
group by ID
having count(ID)>1
order by ID;
GO
/*
ID
-----------
39990
39991
39992
39993
39994
39995
39996
39997
39998
39999
(10 row(s) affected)
Table 'TestA'. Scan count 2, logical reads 279, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
*/
求更高效的方案。
梦里花落0921
神不在的星期二
largeQ
不负相思意
繁星点点滴滴
互换的青春
哔哔one
梵蒂冈之花
狐的传说
江户川乱折腾
相关分类