SQL工作奇怪

时间:2017-09-21 09:01:41

标签: sql

执行此SQL代码时:

select id, opis, vidrabota, tipprov, hitnost, valuta, drzava, zbirnaprov, tip_zbirprov, kanal
from dev_1450autoebanktip
where opis is null or Opis like case when isnull('','') = '' then Opis else '%' + '' + '%' end
and VidRabota = case when isnull('','') = '' then VidRabota else '' end
and TipProv = case when isnull(0,0) = 0 then TipProv else 0 end
and Valuta = case when isnull('','') = '' then Valuta else '' end
and drzava is null or Drzava = case when isnull('','') = '' then Drzava else '' end

我得到了这组结果: enter image description here

但是当我再添加一个条件(最后一行)时:

select id, opis, vidrabota, tipprov, hitnost, valuta, drzava, zbirnaprov, tip_zbirprov, kanal
from dev_1450autoebanktip
where opis is null or Opis like case when isnull('','') = '' then Opis else '%' + '' + '%' end
and VidRabota = case when isnull('','') = '' then VidRabota else '' end
and TipProv = case when isnull(0,0) = 0 then TipProv else 0 end
and Valuta = case when isnull('','') = '' then Valuta else '' end
and drzava is null or Drzava = case when isnull('','') = '' then Drzava else '' end
and KANAL = case when isnull(0,0) = 0 then KANAL else 0 end

我在结果中丢失了一行。造成这种变化的原因是什么?

enter image description here

1 个答案:

答案 0 :(得分:1)

Kanal在最后一行是NULL。

$save = "INSERT INTO trans_details 
        (badge_id,user_id,comp_id,amount,cash,subsidy,trans_date) 
        values('$badge_id','$user_id','$cid',$amount,$total_need,'$amount',$stamp)"; 
$result = sqlsrv_query($conn, $save);

归结为

and KANAL = case when isnull(0,0) = 0 then KANAL else 0 end

但是对于NULL不是这样,因为NULL是未知值。将null与null进行比较时,结果既不是真也不是假,而是未知。因此,添加的标准驳回了最后的记录。

我想添加一件事:混合and KANAL = KANAL AND时使用括号。例如

OR

装置

a = b or a = c and d = e

因为a = b or (a = c and d = e) 优先于AND,您可能希望表达式为

OR

使用括号以避免任何错误。