我有以下 View 作为另一个系统的接口(interface)。请注意,它是一个 View ,而不是一个表,所以我不能更改架构和添加主键。
view NODE (
STATE varchar(255), -- can be null
SIBLING_STATE varchar(255) -- can also be null
)
然后我需要在 SIBLING_STATE 列上将此表连接到自身以找到具有该状态的所有其他节点。
select n.STATE, n.SIBLING_STATE, ns.STATE from NODE n
left join NODE ns where n.SIBLING_STATE = ns.STATE
然后我需要将这个上游传递给其他进行分组和计数的 View ,但所有这些都与本次讨论无关。
我遇到的问题是,作为次要要求,我需要检查是否由于此连接而实际检索了任何兄弟记录,但如上所述,任何节点的 STATE
和/或者 SIBLING_STATE
可以为空。
select
n.STATE,
n.SIBLING_STATE,
ns.STATE,
case when (ns.<something> is not null) then 'found' else 'not found' end as IS_FOUND
from NODE n
left join NODE ns where n.SIBLING_STATE = ns.STATE
我如何实际检查 ns
记录是否存在?我无法对 ns.STATE
或 ns.SIBLING_STATE
进行 null 检查,因为它们本身可能都是 null:
-- Can't do this because ns.SIBLING_STATE might be null
case when (ns.SIBLING_STATE is not null) then 'found' else 'not found' end as IS_FOUND
-- Can't do this because ns.STATE might be null
case when (ns.STATE is not null) then 'found' else 'not found' end as IS_FOUND
关于如何对整个记录进行空检查的任何想法,例如如果我可以说的话?
case when (recordExists(ns)) then 'found' else 'not found' end as IS_FOUND
感谢任何类型的答案,包括特定于方言的答案(即仅适用于 mysql/sql-server/postgresql)。
编辑:澄清这是一个 View
最佳答案
像这样
select
n.STATE,
n.SIBLING_STATE,
ns.STATE,
case when (ns.NeverNull is not null) then 'found' else 'not found' end as IS_FOUND
from NODE n
left join From (Select *, 'A' As NeverNull From NODE) ns
ON n.SIBLING_STATE = ns.STATE
关于sql - 在 Left Join 期间对整行进行空检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49715437/