SQL語句NOT IN判斷條件注意事項
sql語句not in判斷條件注意事項
問題描述:mysql數據庫,存在兩個表org表和kdorg表,用於存儲組織信息。現在我需要從org表找出組織,條件為該組織不在kdorg表里。
sql語句:select o.orgno o.orgname from org o where orgno not in(select kd.orgno from kdorg kd);
明明org表里存在一些組織,該組織的組織編號不存在於kdorg表,但查詢結果就是0條記錄。搞了一天,也沒搞出問題在哪,頭都大了,就是一條簡單的sql語句,條件滿足,為何就是不對呢?
原因分析:是因為kdorg表存在一條記錄,該記錄的orgno為null,導致查詢結果為空。把orgno為null的記錄從kdorg表刪除,該sql語句就能成功查詢出所需信息。
總結: not in /in(不能存在null的字段,否則會導致條件失效,sql語句查不出所需數據)
改進:(1)select o.orgno o.orgname from org o where orgno not in(select kd.orgno from kdorg kd where kd.orgno is not null);
(2)保證子查詢結果中不存在null。