我需要确定表 OtherItems 中的哪些项目也存在于 ItemMain 中,哪些不存在。
问题是有些 UPC 的开头是 0,有些则没有。
所以我尝试了这个查询,但结果看起来不太好。
SELECT * from OtherItems
WHERE UPC like '0%' and upc not in(select '0' + UPC from itemmain)
Or UPC not in(select UPC from itemmain))
有人可以指导我在这里做错了什么吗?
我需要确定表 OtherItems 中的哪些项目也存在于 ItemMain 中,哪些不存在。
问题是有些 UPC 的开头是 0,有些则没有。
所以我尝试了这个查询,但结果看起来不太好。
SELECT * from OtherItems
WHERE UPC like '0%' and upc not in(select '0' + UPC from itemmain)
Or UPC not in(select UPC from itemmain))
有人可以指导我在这里做错了什么吗?
select *
from OtherItems
where not exists ( select *
from itemmain
where UPC=OtherItems.UPC or '0'+UPC=OtherItems.UPC )
也许:
select *
from OtherItems
where ( UPC like '0%'
and not exists (select * from itemmain where '0'+UPC=OtherItems.UPC) )
or ( UPC not like '0%'
and not exists (select * from itemmain where UPC=OtherItems.UPC) )
UPC 通常没有字母字符。为什么不将它们转换为一个数字,如果它存在于一个而不是另一个上,它会删除前导零?
SELECT *
FROM OtherItems A
WHERE NOT EXISTS
(SELECT 1
FROM ItemMain B
WHERE CAST(A.UPC as DECIMAL(18)) = CAST(B.UPC) AS DECIMAL(18))
您的逻辑需要在 OR 周围加上括号:
SELECT * from OtherItems
WHERE UPC like '0%' and
(upc not in(select '0' + UPC from itemmain)
Or UPC not in(select UPC from itemmain))
使用括号, AND 优先,所以你有效地得到(A AND B) OR C