【发布时间】:2015-07-29 16:04:14
【问题描述】:
我有下表,其中三个字段如下所示:
表:Testing
create table testing
(
colnum varchar(10),
coldate date,
colid int
);
插入:
insert into testing values('111','2015-01-01',1);
insert into testing values('111','2015-01-02',1);
insert into testing values('111','2015-01-03',1);
insert into testing values('111','2015-01-04',1);
insert into testing values('111','2015-01-05',1);
insert into testing values('222','2015-01-01',1);
insert into testing values('333','2015-01-01',1);
索引创建:
create clustered index id_idx on testing(colid);
create nonclustered index date_nidx on testing(coldate);
create nonclustered index num_nidx on testing(colnum);
注意:现在我想显示仅在特定日期和特定 ID 而不是其他日期的记录。
例如:我想显示ONLY IN指定日期和ID但不显示其他日期的记录。
给定日期:2015-01-01
给定 ID:1
为此我写了以下查询:
select * from testing
where coldate in ('2015-01-01')
and coldid = 1
and colnum not in(select colnum from testing where coldid = 1 and
coldate in('2015-01-02','2015-01-03','2015-01-04'
'2015-01-05');
结果:
colnum coldate colid
--------------------------
222 2015-01-01 1
333 2015-01-01 1
说明:查询显示两条记录,因为两条记录都只有特定日期和 id 但记录 111 未显示,因为它也属于其他日期您可以在上表中看到。
上述查询对我来说很好但是需要更多时间来执行数十亿条记录。
【问题讨论】:
-
根据你的情况,
111也应该返回? -
你的表有索引吗?
-
请张贴创建索引脚本。
-
试试这个:
create nonclustered index nci_testing on testing (colid, coldate) include(colnum) -
是的,这将对
INSERT和DELETE产生影响。但是您现在可以删除您创建的其他索引。
标签: sql sql-server sql-server-2008 sql-server-2008-r2