半瓶内容

 results 1 - 1 of about 1 for 慎用Oracle的not in谓词. (0.305 seconds) 

慎用Oracle的not in谓词

帮财务人员处理数据,一个是ERP系统中的账面数据,一个是税务局给的官方数据,一张EXCEL表,想找出两边不匹配的数据。

据说EXCEL2007版本已经提供了这种比对的功能,但无奈数据量太大,操作起来巨慢如牛,而WPS2009似乎还没这个功能,于是导入数据库中新建一个表存储这些数据来比对。

开始写了个SQL来查询税务有而ERP系统中没有的数据:

select * from tab_excel  where taxcode not in
(select erpcode from tab_excel)

正常,然后反过来查ERP中存在而税务系统中不存在的数据:

select * from tab_excel  where erpcode not in
(select taxcode from tab_excel)

返回0条数据,很奇怪,然后马上想到了是null的问题,taxcode必然存在值为null的记录,oracle中和null比较的返回值是unkown,所以才无法匹配。

于是修改SQL语句如下:

select * from tab_excel tout  where not exists
(select 1 from tab_excel where taxcode=tout.erpcode)

结果正常。

not in (...) 括号中的返回值不能存在null值,是Oracle SQL开发的一条铁律,如果不能确定返回结果一定无null值,还是改写为not esists吧。而且not in效率低下,一般不能用到索引,生产环境的程序最好不要使用。


Leave a Comment