SQL查询根据条件返回值不起作用

时间:2019-05-04 04:04:32

标签: sql oracle

当(srf1.shipment_refnum_qual_gid ='DUCAB.EXCISE_INVOICE_ATTACHED'和srf2.shipment_refnum_qual_gid ='DUCAB.BOL_ATTACHED'的两个值都等于Y时,我的查询不应返回1。为Y。

当前,当两个值均为N或其中一个值为N时,我的查询正在运行,但是只要我的refnum的值为Y,则查询将不起作用。

我是SQL的新手,请帮助我理解。

我尝试使用IN,但无法正常工作。

select 1 
from shipment sh, shipment_refnum srf1, shipment_refnum srf2, shipment_remark srk
where 
    sh.shipment_gid = srf1.shipment_gid
    and sh.shipment_gid = srf2.shipment_gid 
    and srf1.shipment_gid = srk.shipment_gid 
    and srf2.shipment_gid = srk.shipment_gid
    and srf1.shipment_refnum_qual_gid = 'DUCAB.EXCISE_INVOICE_ATTACHED'
    and srf2.shipment_refnum_qual_gid = 'DUCAB.BOL_ATTACHED'
    and srf1.shipment_refnum_value in ('Y','N')
    and srf2.shipment_refnum_value in ('Y','N')
    and srk.remark_qual_gid = 'DUCAB.REASON_FOR_REJECTION'
    and srk.remark_text not in ('NO_VALUE')
    and sh.shipment_gid = 'DUCAB.20110'

所以,我想要的结果是 'DUCAB.EXCISE_INVOICE_ATTACHED'的shipment_refnum_value为Y,'DUCAB.BOL_ATTACHED'的shipment_refnum_value为Y,则我的查询不应返回1。

1 个答案:

答案 0 :(得分:1)

首先,您的查询仅返回1,没有其他上下文。通常,选择查询将返回多个记录,这些记录显示来自不同表的不同列。因此,我正在更改您的查询,以显示似乎符合您所要查找的内容的装运和参考编号...只有srf1或srf2可以=“ Y”,而不能同时=“ Y”。

第二,我正在将您的查询调整为使用JOIN语法,而不是通过WHERE声明。

第三,通过传递关联,如果A = B并且B = C,则A =C。
所以从

sh.Shipment_gid = srf1.Shipment_gid and srf1.shipment_gid = srk.shipment_gid 

然后

sh.Shipment_gid = srk.shipment_gid 




select 
      sh.shipment_gid,
      1 
   from 
      shipment sh
         JOIN shipment_refnum srf1
            ON sh.shipment_gid = srf1.shipment_gid
           and srf1.shipment_refnum_qual_gid = 'DUCAB.EXCISE_INVOICE_ATTACHED'
           and srf1.shipment_refnum_value in ('Y','N')
         JOIN shipment_refnum srf2
            ON sh.shipment_gid = srf2.shipment_gid
           and srf2.shipment_refnum_qual_gid = 'DUCAB.BOL_ATTACHED'
           and srf2.shipment_refnum_value in ('Y','N')
         JOIN shipment_remark srk
            ON sh.shipment_gid = srk.shipment_gid 
           and srk.remark_qual_gid = 'DUCAB.REASON_FOR_REJECTION'
           and srk.remark_text not in ('NO_VALUE')
   where 
          sh.shipment_gid = 'DUCAB.20110'
      -- THIS Clause makes sure only ONE of them is a Y 
      -- hence not equal to each other.
      AND srf1.shipment_refnum_value <> srf2.shipment_refnum_value