如何比较表中同一行下的多个列?

时间:2015-06-09 07:42:39

标签: oracle plsql

在where子句中,表的以下列不应该相等。

  • cd_delivery_address
  • cd_mail_delivery_address
  • cd_st_code
  • cd_mail_st_code
  • cd_zip
  • cd_mail_zip

请找到我的代码段来实现此目的:

     select * from table cd
     where
(
(cd_mail_delivery_address <> cd_delivery_address or    
(cd_mail_delivery_address is null and cd_delivery_address is not null) or
(cd_mail_delivery_address is not null and cd_delivery_address is null)
)
and (
cd.cd_city <> cd.cd_mail_city or 
(cd.cd_city is null and cd_mail_city is not null) or 
(cd_city is not null and cd_mail_city is null))
and (
cd.st_code <> cd.cd_mail_st_code or 
(cd.st_code is null and cd_mail_st_code is not null) or 
(st_code is not null and cd_mail_st_code is null)
)
and (
cd.cd_zip <> cd.cd_mail_zip or 
(cd.cd_zip is null and cd_mail_zip is not null) or 
(cd_zip is not null and cd_mail_zip is null)
)
)

所有列都是varchar2,我得到了此代码的正确输出。但它是比较pl sql中多个列的更好方法吗?我能改进这段代码吗?任何建议都会有所帮助。

2 个答案:

答案 0 :(得分:1)

您可以使用以下内容替换您的空检查:

...
NVL(cd_mail_delivery_address,'_') <> NVL(cd_delivery_address,'_')
...

它确实更具可读性,但我不确定查询效率

答案 1 :(得分:0)

我使用连接在两列中完成了它:

select a.cd_delivery_address,b.cd_mail_delivery_address 
from cd a inner join cd b 
where a.cd_delivery_address <> b.cd_mail_delivery_address and
a.cd_delivery_address = b.cd_delivery_address

这里将忽略空检查条件并减少条件数,但由于涉及连接,因此会对性能产生影响。