刚接触数据库,有点晕
select * from table1 b ,score a where a.score <> b.score 这个语句,表table1是score复制过去的,那这样的语句运行的结果不应该是空集嘛?那为什么我实际运行的结果不是呢?
select * from table1 b ,score a where a.score <> b.score 这个语句,表table1是score复制过去的,那这样的语句运行的结果不应该是空集嘛?那为什么我实际运行的结果不是呢?
id------score
1---------1
2---------2按楼主的语句先产生的笛卡尔积如下a.score-------b.score
1-----------------1
1-----------------2 --不同
2-----------------1
2-----------------2 --不同找出的记录会有两条
select * from table1 b cross join score a where a.score <> b.score
那如果要实现对score这一列的比较,正确的语句应该怎么写呢?
select * from table1 b ,score a where a.关联字段 = b.关联字段 and a.score <> b.score--不过这样意义不大,不管A表数据如何,这个查询始终的空!
我实际运行的结果 跟你标示出的很像
那如果我要实现两列之间的依次比较 而不是先笛卡尔 语句应该是怎样的呢?
--除非Score表的字段Score值对于所有的记录都一样,不然以下就肯定会有结果集
select * from table1 b ,score a where a.score <> b.score--举例create table #A(Score int, re varchar(10))
--Score不一样的情况
insert into #A
select 1,'2' union all
select 2,'3'select * into #B from #A
--结果
select * from #A as a,#B as b where a.Score<>b.score
Score re Score re
----------- ---------- ----------- ----------
2 3 1 2
1 2 2 3(2 行受影响)
----------------Score一样的情况
delete from #Ainsert into #A
select 1,'2' union all
select 1,'3'select * into #C from #A--结果
select * from #A as a,#C as b where a.Score<>b.scoreScore re Score re
----------- ---------- ----------- ----------(0 行受影响)
select * from table1 b
left join score a
on a.tid=b.tid
where a.score <> b.score
select * from table1
except
select * from table2
如果用2表连接的方法,内部总会先建立笛卡尔积的
还有么用游标
数据库连接是笛卡尔集,排除score 相等的罢了