[英]Oracle SQL ignores condition in WHERE clause
我有这个简单的 SQL 查询部分
where aia.invoice_num in (:invoice_num) or aia.invoice_num is null
and ipa.payment_date between (:start_date) and (:end_date) or ipa.payment_date >= (:start_date) or (:start_date is null and :end_date is null)
and ipa.PAYEE_NAME in (:payee) or :payee is null
我有 4 个参数, invoice_num
、 start_date
、 end_date
和Payee
,我希望它就像一个过滤器,如果存在上述条件之一,则必须应用它,如果不存在,则必须忽略它,但它只是不'按预期工作,如果我传递invoice_num
结果将是所有发票,无论其他参数是否存在或为空,我如何强制每个条件(如果存在)并忽略它(如果为null
)?
您的查询不起作用,因为:
AND
的运算符优先级高于OR
,这意味着它被评估为:
where ( aia.invoice_num in (:invoice_num) ) or ( aia.invoice_num is null and ipa.payment_date between (:start_date) and (:end_date) ) or ( ipa.payment_date >= (:start_date) ) or (:start_date is null and:end_date is null and ipa.PAYEE_NAME in (:payee) ) or (:payee is null )
因此,如果任何OR
条件为真,则可以忽略其余条件。
您比较aia.invoice_num is null
而不是:invoice_num IS NULL
。
要修复它,您可以使用:
WHERE ( aia.invoice_num = :invoice_num OR :invoice_num IS NULL )
AND ( ipa.payment_date >= :start_date OR :start_date IS NULL )
AND ( ipa.payment_date <= :end_date OR :end_date IS NULL )
AND ( ipa.PAYEE_NAME = :payee OR :payee IS NULL )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.