簡體   English   中英

比較SQL中的int列

[英]Comparing int columns in SQL

我有兩個int列。 Org表中的OrgNum和Service表中的ServiceNum。 OrgNum有1892個不同的行。 ServiceNum有2362個不同的行。

select distinct orgnum from org
where orgnum in (select distinct servicenum from services)

上面的查詢返回3條記錄。

select distinct orgnum from org
where orgnum not in (select distinct servicenum from services)

該查詢不返回任何記錄。

這怎么可能,因為ServiceNum中存在OrgNum或不存在。 兩者都不可行。 在SQL中有比較int的其他方法嗎?

當子查詢返回任何 null值時, not in具有奇怪的行為。 在這種情況下,不返回任何行。

因此,我建議您始終使用not exists

select distinct o.orgnum
from org o
where not exists (select 1 from services s where o.orgnum = s.servicenum);

此行為是可以解釋的。 在SQL中, null通常具有“ unkonwn”而不是“ missing”的語義。 所以:

1 in (2, 3)            -- returns false (you know it is not there)
1 in (null, 2, 3)      -- returns null (could be there or not).  BUT `null` is treated like false in where
1 not in (2, 3)        -- returns true
1 not in (null, 2, 3)  -- returns null.  But this is treated as false.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM