日期:2014-05-16  浏览次数:20432 次

not exists用法 再举例

这个鸟东西,每次用它都郁闷啊!

?

举个例子吧,假如有2张表,表结构一样,一张称为tableOld,一张称为tableNew。

?

其中有个字段ID。

?

tableOld有1000条数据,而tableNew数据有1050条数据。

?

其实在新表中的1050条数据包括了旧表的1000条数据,那么现在想把这50条数据找出。

?

该如何办呢?

?

错误解法:

?

select * from  tableNew n
where   not exists
(
	select * from  tableOld  o  inner join  n on n.id=o.id
)
?

?

没什么大错误,只是括号里面不能这样写,要写笛卡尔积,而不能用inner join这种方式。

?

?

正解一:not exists

?

?

select * from  tableNew n
where   not exists
(
	select * from  tableOld o where n.id=o.id
)
?

?

正解二:not in(提前想好要判断哪几个字段不在某个集合里,这里想的是id)

?

?

select * from  tableNew n
where   id not in 
(
	select id from  tableOld  o
)
?

?

ps:这2张表一般是经过整理的临时表。