--测试代码创建的缘由(测试代码的作用):左右连接和is null 结合妙用
--测试代码运用到的核心技术 :left join on 、 is null
--测试代码创建的相关资料、url:QQ群
date1 value1 2008-1-1 A
2008-1-1 B
2008-1-1 C
2008-1-2 A
2008-1-2 B
2008-1-2 C
date2 value2 2008-1-1 A
2008-1-1 B
2008-1-2 A
2008-1-2 B
2008-1-2 C
如何比较快速得到:
2008-1-1 C
--测试代码创建日期(2008-11-18)
--测试代码所需对象的创建代码
create table table1 (date1 char(8),value1 char(1))
go
create table table2 (date2 char(8),value2 char(1))
go
insert table1 values('2008-1-1','A')
insert table1 values('2008-1-1','B')
insert table1 values('2008-1-1','C')
insert table1 values('2008-1-2','A')
insert table1 values('2008-1-2','B')
insert table1 values('2008-1-2','C')
insert table2
values('2008-1-1','A')
insert table2 values('2008-1-1','B')
insert table2 values('2008-1-2','A')
insert table2 values('2008-1-2','B')
insert table2 values('2008-1-2','C')
--内容
--第一眼看去,感觉 要用not in 只怪自己技术不够醇厚啊。居然想这么想了:
select * from table1 where not in (select * from table2)
--语法就不对了。
--就换成exists ,呵呵,结果为空,去掉not
居然是table1中所有数据,了解到exists是通过单列来判断的,不是整行整行的来判断的。
select * from table1 where not exists (select * from table2)
--用join on 得到table2中的所有行,不行
select * from table1 join table2 on date1=date2 and
value1=value2
--冥思苦想,最终未果,求助QQ群。一大侠给出了mysql语句,说的出结果了。虽然没有怎么接触mysql,一看,嘿,效率好像还不错。
select t1.date,t1.value from t1 left join t2 using (date,value)
where t1.value is null or t2.value is null
--改!不用 date1 is null也行。
select date1,value1 from table1 left join table2 on date1=date2 and
value1=value2 where value2 is
null
--分析:
--当两个表连接起来对比查询的时候,table2中没有table1中的相应的行的时候,table2会生成与之相应的null行,所以,与表2中null行相应的表1中的行就是要的结果
--测试代码所有的对象清理代码
drop table table1
drop table table2
--备注:讨论能够很快解决问题,讨论之前仔细思考,体会会更加深刻。
(本来是带高亮显示的,新浪规定了字数啊,居然样式代码也算字数,所字数太多。:-()