+ -
当前位置:首页 → 问答吧 → 查找记录是否是新纪录的问题,应该不难的,想找最快的方法

查找记录是否是新纪录的问题,应该不难的,想找最快的方法

时间:2011-11-07

来源:互联网

表table_a(id,ip,batch_no)
batch_no 是批次好,插入table_a的时候,是一批一批的插入的,同一个批次插入的,bach_no相同

表数据如下:
id ip batch_no
1 10.0.0.1 1
2 10.0.0.2 1
3 10.0.0.3 1

4 10.0.0.1 2
5 10.0.0.2 2
6 10.0.0.3 2
7 10.0.0.4 2
8 10.0.0.5 2
9 10.0.0.6 2


我的需求是,找出批次号最新的数据中,那些ip数据时一起没有出现过的,例子里面新出现的ip是 10.0.0.4,10.0.0.5, 10.0.0.6

最笨的方法就是用一个循环来搜索。。。我想知道是否有更快的方法?
数据在access中,

作者: LinuxCard   发布时间: 2011-11-07

SQL code
select * from table_a a where not exists(select 1 from table_a where batch_no-a.batch_no and id>a.id)

作者: qianjin036a   发布时间: 2011-11-07

access的语法不太一样 建议去其他数据库版问问。

作者: fredrickhu   发布时间: 2011-11-07

错了.~~~~~
SQL code
select ip from table_a a 
where batch_no=(select max(batch_no) from table_a)
and not exists(select 1 from table_a where batch_no<a.batch_no and ip=a.ip)

作者: qianjin036a   发布时间: 2011-11-07

有个笔误:
我的需求是,找出批次号最新的数据中,那些ip数据时一起没有出现过的

应该是
我的需求是,找出批次号最新的数据中,那些ip数据时以前没有出现过的

作者: LinuxCard   发布时间: 2011-11-07

此语句在ACCESS里也能用
SQL code
create table table_a(id int,ip varchar(20),batch_no int)
insert into table_a select 1,'10.0.0.1',1
insert into table_a select 2,'10.0.0.2',1
insert into table_a select 3,'10.0.0.3',1
insert into table_a select 4,'10.0.0.1',2
insert into table_a select 5,'10.0.0.2',2
insert into table_a select 6,'10.0.0.3',2
insert into table_a select 7,'10.0.0.4',2
insert into table_a select 8,'10.0.0.5',2
insert into table_a select 9,'10.0.0.6',2
go
select ip from table_a a 
where batch_no=(select max(batch_no) from table_a)
and not exists(select 1 from table_a where batch_no<a.batch_no and ip=a.ip)
/*
ip
--------------------
10.0.0.4
10.0.0.5
10.0.0.6

(3 行受影响)

*/
go
drop table table_a

作者: qianjin036a   发布时间: 2011-11-07

SQL code
use Tempdb
go
--> --> 
 
if not object_id(N'T') is null
    drop table T
Go
Create table T([id] int,[ip] nvarchar(8),[batch_no] int)
Insert T
select 1,N'10.0.0.1',1 union all
select 2,N'10.0.0.2',1 union all
select 3,N'10.0.0.3',1 union all
select 4,N'10.0.0.1',2 union all
select 5,N'10.0.0.2',2 union all
select 6,N'10.0.0.3',2 union all
select 7,N'10.0.0.4',2 union all
select 8,N'10.0.0.5',2 union all
select 9,N'10.0.0.6',2
Go
Select * from T AS a WHERE NOT EXISTS(SELECT 1 FROM T WHERE [batch_no]>a.[batch_no] or ([batch_no]<a.[batch_no] AND IP=a.IP))
/*
id    ip    batch_no
7    10.0.0.4    2
8    10.0.0.5    2
9    10.0.0.6    2
*/

作者: roy_88   发布时间: 2011-11-07