[英]SQL Server - How to do Inner Join when condition could be empty?
I am trying to get the Country from my factories AddressID directly in one Query with an Inner join.我试图在一个带有内部连接的查询中直接从我的工厂 AddressID 获取国家/地区。 My problem is that the AddressID could be an empty string.
我的问题是 AddressID 可能是一个空字符串。
How do i check that and do some kind of exception or something similar?我如何检查并执行某种异常或类似的操作? I if address ID is empty i need an empty string as result for f.Country.
如果地址 ID 为空,我需要一个空字符串作为 f.Country 的结果。
This is my query for now, but if AddressID = '' then the row is not showing up in my result.这是我现在的查询,但如果 AddressID = '' 那么该行不会显示在我的结果中。
SELECT o.FactoryID,o.Name,o.Rating,o.ProductCategory,o.Emissions,o.LatestChanges,o.AddressID,o.ProductTags,f.Country
FROM FactoryHistory o
INNER JOIN AddressHistory f on f.AddressID = o.AddressID
WHERE NOT o.LatestChanges = 'Deleted' AND o.IsCurrent = 1 AND f.IsCurrent = 1
I something in my question is missing or unclear, just let me know!我的问题中缺少某些内容或不清楚,请告诉我!
Just left join
:刚
left join
:
SELECT o.FactoryID, o.Name, o.Rating, o.ProductCategory, o.Emissions, o.LatestChanges, o.AddressID, o.ProductTags, f.Country
FROM FactoryHistory o
LEFT JOIN AddressHistory f on f.AddressID = o.AddressID AND f.IsCurrent = 1
WHERE NOT o.LatestChanges = 'Deleted' AND o.IsCurrent = 1
If you still want to filter out factories whose AddressID
is not null
(assuming that by empty you mean null
) and that do not exist in the address table, than you can add a condition in the WHERE
clause:如果您仍然想过滤掉
AddressID
不为null
工厂(假设空的意思是null
)并且地址表中不存在,那么您可以在WHERE
子句中添加一个条件:
WHERE
NOT o.LatestChanges = 'Deleted'
AND o.IsCurrent = 1
AND (o.AddressID IS NULL OR f.AddressID IS NOT NULL)
It might be clearer with a negation:否定可能更清楚:
WHERE
NOT o.LatestChanges = 'Deleted'
AND o.IsCurrent = 1
AND NOT (o.AddressID IS NOT NULL AND f.AddressID IS NULL)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.