我列出2个表的 关联数据 数据量 比较大 我自己写的 查询速度慢死了A表
ID 年份
1 2007-5-7
2 2008-5-7
3 2008-5-8
B表
ID 年份
1 2007-5-7
1 2009-5-7
1 2010-5-8
2 2008-5-7 我结果 只要A表里面的数据
3 2008-5-8
只要 A表中 通过 ID和月份 能有一个关联到 这条数据就不要。
本人绝对结贴 求高手解答 结果正确,速度还算可以 马上结贴。
ID 年份
1 2007-5-7
2 2008-5-7
3 2008-5-8
B表
ID 年份
1 2007-5-7
1 2009-5-7
1 2010-5-8
2 2008-5-7 我结果 只要A表里面的数据
3 2008-5-8
只要 A表中 通过 ID和月份 能有一个关联到 这条数据就不要。
本人绝对结贴 求高手解答 结果正确,速度还算可以 马上结贴。
create table #A表
(ID int,年份 datetime)
insert #A表
select 1 ,'2007-5-7' union all
select 2 ,'2008-5-7' union all
select 3 ,'2008-5-8'
create table #B表
(ID int,年份 datetime)
insert #B表
select 1 ,'2007-5-7' union all
select 1 ,'2009-5-7' union all
select 1 ,'2010-5-8' union all
select 2 ,'2008-5-7' select A.* from #A表 as a Left join #B表 as b
on a.id=b.id and a.年份=b.年份
where b.id is null--ID 年份
------------- -----------------------
--3 2008-05-08 00:00:00.000
--
--(1 row(s) affected)這樣?
select ID, 年份 from taba
except
select ID, 年份 from tabb
a.* from a left join b
on
a.id=b.id and a.年份=b.年份
where
b.id is null
--这个可以在连接字段加索引
go
create table A表
(
ID int,
年份 datetime
)
insert A表
select 1 ,'2007-5-7' union all
select 2 ,'2008-5-7' union all
select 3 ,'2008-5-8'
go
if object_id(N'B表',N'U') is not null drop table B表
create table B表
(
ID int,
年份 datetime
)
insert B表
select 1 ,'2007-5-7' union all
select 1 ,'2009-5-7' union all
select 1 ,'2010-5-8' union all
select 2 ,'2008-5-7'
goselect * from A表
select * from B表
/*
我结果 只要A表里面的数据
3 2008-5-8
只要 A表中 通过 ID和月份 能有一个关联到 这条数据就不要。
本人绝对结贴 求高手解答 结果正确,速度还算可以 马上结贴。
*/
select A表.* from (
select Id,month(年份) as ab from A表
except
select Id,month(年份) as ab from B表
)a left join A表 on A表.Id=a.Id
select A表.* from (
select Id,month(年份) as ab from A表
except
select Id,month(年份) as ab from B表
)a left join A表 on A表.Id=a.Id
--3 2008-05-08 00:00:00.000
--SQL Server 分析和编译时间:
-- CPU 时间 = 0 毫秒,占用时间 = 8 毫秒。
--
--(1 行受影响)
--表 'A表'。扫描计数 2,逻辑读取 2 次,物理读取 0 次,预读 0 次,lob 逻辑读取 0 次,lob 物理读取 0 次,lob 预读 0 次。
--表 'B表'。扫描计数 1,逻辑读取 3 次,物理读取 0 次,预读 0 次,lob 逻辑读取 0 次,lob 物理读取 0 次,lob 预读 0 次。
--
--SQL Server 执行时间:
-- CPU 时间 = 0 毫秒,占用时间 = 0 毫秒。
select a.* from A表 as a Left join B表 as b
on a.id=b.id and a.年份=b.年份 where b.年份 is null
--3 2008-05-08 00:00:00.000
--SQL Server 分析和编译时间:
-- CPU 时间 = 0 毫秒,占用时间 = 2 毫秒。
--
--(1 行受影响)
--表 'B表'。扫描计数 1,逻辑读取 3 次,物理读取 0 次,预读 0 次,lob 逻辑读取 0 次,lob 物理读取 0 次,lob 预读 0 次。
--表 'A表'。扫描计数 1,逻辑读取 1 次,物理读取 0 次,预读 0 次,lob 逻辑读取 0 次,lob 物理读取 0 次,lob 预读 0 次。
--
--SQL Server 执行时间:
-- CPU 时间 = 0 毫秒,占用时间 = 0 毫秒。select * from A表 where checksum(*) not in(select checksum(*) from B表)
--SQL Server 分析和编译时间:
-- CPU 时间 = 6 毫秒,占用时间 = 6 毫秒。
--
--(1 行受影响)
--表 'B表'。扫描计数 1,逻辑读取 3 次,物理读取 0 次,预读 0 次,lob 逻辑读取 0 次,lob 物理读取 0 次,lob 预读 0 次。
--表 'A表'。扫描计数 1,逻辑读取 1 次,物理读取 0 次,预读 0 次,lob 逻辑读取 0 次,lob 物理读取 0 次,lob 预读 0 次。
--
--SQL Server 执行时间:
-- CPU 时间 = 0 毫秒,占用时间 = 1 毫秒。
where not exists
(select 1 from b where a.id=b.id and a.年份=b.年份)