现有A B 两表 A表记录如
name no times date
张三 002 1 2008-12-01
张三 002 2 2008-12-22
张三 002 3 2009-12-01
李四 010 1 2005-01-01
王五 022 2 2004-01-23
B表记录如
name no times date
张三 002 1 2008-12-01
张三 002 2 2008-12-22
张三 002 3 2009-12-01
张三 002 4 2010-12-01
张三 002 5 2010-12-22
张三 002 5 2010-12-29 (次数一样,日期不一样)
李四 010 2 2005-12-23
王五 022 4 2007-01-23
王五 022 5 2007-01-25我要查出B表里A表没有的记录这个SQL怎么写啊。。
name no times date
张三 002 1 2008-12-01
张三 002 2 2008-12-22
张三 002 3 2009-12-01
李四 010 1 2005-01-01
王五 022 2 2004-01-23
B表记录如
name no times date
张三 002 1 2008-12-01
张三 002 2 2008-12-22
张三 002 3 2009-12-01
张三 002 4 2010-12-01
张三 002 5 2010-12-22
张三 002 5 2010-12-29 (次数一样,日期不一样)
李四 010 2 2005-12-23
王五 022 4 2007-01-23
王五 022 5 2007-01-25我要查出B表里A表没有的记录这个SQL怎么写啊。。
select 1 from a where a.name=b.name and a.no=b.no and a.times=b.times and a.date=b.date)
except
select * from ta
from b
where not exists(select 1 from a where name=b.name and no=a.no and times=a.times and [date]=t.[date])
-- Author :fredrickhu(小F,向高手学习)
-- Date :2010-05-25 15:58:19
-- Version:
-- Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86)
-- Nov 24 2008 13:01:59
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 3)
--
----------------------------------------------------------------
--> 测试数据:[a]
if object_id('[a]') is not null drop table [a]
go
create table [a]([name] varchar(4),[no] varchar(3),[times] int,[date] datetime)
insert [a]
select '张三','002',1,'2008-12-01' union all
select '张三','002',2,'2008-12-22' union all
select '张三','002',3,'2009-12-01' union all
select '李四','010',1,'2005-01-01' union all
select '王五','022',2,'2004-01-23'
--> 测试数据:[B]
if object_id('[B]') is not null drop table [B]
go
create table [B]([name] varchar(4),[no] varchar(3),[times] int,[date] datetime)
insert [B]
select '张三','002',1,'2008-12-01' union all
select '张三','002',2,'2008-12-22' union all
select '张三','002',3,'2009-12-01' union all
select '张三','002',4,'2010-12-01' union all
select '张三','002',5,'2010-12-22' union all
select '张三','002',5,'2010-12-29' union all
select '李四','010',2,'2005-12-23' union all
select '王五','022',4,'2007-01-23' union all
select '王五','022',5,'2007-01-25'
--------------开始查询--------------------------
select * from b where checksum(*) not in (select checksum(*) from a)
----------------结果----------------------------
/* name no times date
---- ---- ----------- -----------------------
张三 002 4 2010-12-01 00:00:00.000
张三 002 5 2010-12-22 00:00:00.000
张三 002 5 2010-12-29 00:00:00.000
李四 010 2 2005-12-23 00:00:00.000
王五 022 4 2007-01-23 00:00:00.000
王五 022 5 2007-01-25 00:00:00.000(6 行受影响)
*/
用你的SQL在我的数据库里创建2这些数据 ,按你的SQL查出的也是对的。。
但是在我的表里查的时候就查不出来基本上把B表所有的记录都查出来了。。
其实我的意思是。。我想查出 A B两表 NO相同,NAME相同,次数,日期有一个不同或者都不同
的记录。
select * from b where
not exists
(select 1 from a where name=b.name and no=b.no and times=b.times and [date]=b.[date])