关于查询某一部分数据是否出现在另一张表的记录的问题

cyh732 2016-03-06 04:46:32
各位大神,我想请教各位指点我写一个查询命令,命令需要挑选出不包含在另一张表里的记录,所需要挑选的记录我用红色字段标出,主要条件是test_id与tb2_id,test2_time与tb2_time不会同时相同的记录,一直没有想出什么好的办法,请各位指点

所需要表的标意图如下
table1
test_id test_time name
1 2016-01-10 赵一
2 2016-01-10 钱二
1 2016-01-11 孙三
2 2016-01-11 李四


table2
tb2_id tb2_time sex
1 2016-01-10 男
2 2016-01-10 女

为了方便各位测试我把SQL生成临时数据的命令写在下面

create table #table1(test_id int,test_time datetime)
create table #table2(tb2_id int,tb2_time datetime)

insert into #table1 select 1,'2016-01-10'
insert into #table1 select 2,'2016-01-10'
insert into #table1 select 1,'2016-01-11'
insert into #table1 select 2,'2016-01-11'
insert into #table2 select 1,'2016-01-10'
insert into #table2 select 2,'2016-01-10'

--求查询输出

select * from #table1
...全文
157 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
cyh732 2016-03-06
  • 打赏
  • 举报
回复
引用 7 楼 SugarToffee 的回复:
[quote=引用 3 楼 cyh732 的回复:] [quote=引用 1 楼 SugarToffee 的回复:] EXCEPT

select test_id,test_time from #table1 except select tb2_id,tb2_time from #table2
主要是两个表的数据不会相同,时间都会时、分、秒的差别[/quote]

select test_id,test_time from (select * from #table1 left join #table2  on test_id=tb2_id) as a where datediff(day,tb2_time,test_time)>3--如果你要3天不要就这样是几天就大与几天
[/quote] 谢谢了
顾西昂 2016-03-06
  • 打赏
  • 举报
回复
引用 3 楼 cyh732 的回复:
[quote=引用 1 楼 SugarToffee 的回复:] EXCEPT

select test_id,test_time from #table1 except select tb2_id,tb2_time from #table2
主要是两个表的数据不会相同,时间都会时、分、秒的差别[/quote]

select test_id,test_time from (select * from #table1 left join #table2  on test_id=tb2_id) as a where datediff(day,tb2_time,test_time)>3--如果你要3天不要就这样是几天就大与几天
cyh027 2016-03-06
  • 打赏
  • 举报
回复
错了,应该是下面 样
select b.id,b.time1 from tb2 as b
where a.id=b.id and a.time1=b.time1
cyh027 2016-03-06
  • 打赏
  • 举报
回复
select b.id,b.time1 from tb2 as b where a.id=b.id and a.time1=b.time1
cyh027 2016-03-06
  • 打赏
  • 举报
回复
select a.id,a.name,a.time1 from tb1 as a
where not exists(
select b.id,b.time1 from tb2 as b
where a.id=b.id and a.time1=b.time1)
cyh732 2016-03-06
  • 打赏
  • 举报
回复
引用 1 楼 SugarToffee 的回复:
EXCEPT

select test_id,test_time from #table1 except select tb2_id,tb2_time from #table2
主要是两个表的数据不会相同,时间都会时、分、秒的差别
cyh732 2016-03-06
  • 打赏
  • 举报
回复
引用 1 楼 SugarToffee 的回复:
EXCEPT

select test_id,test_time from #table1 except select tb2_id,tb2_time from #table2
首选谢谢楼上的回复,我有个细节自己没说清楚,不好意思。 我这个时间可能需要用datediff计算相差天数,比如同一ID,但是相差天数不大于三天的记录,请问除了用这个计算差集的的写法,有没有用函数对比过滤数据的写法呢?
顾西昂 2016-03-06
  • 打赏
  • 举报
回复
EXCEPT

select test_id,test_time from #table1 except select tb2_id,tb2_time from #table2

34,588

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧