sql - 在 Left Join 期间对整行进行空检查

标签 sql database join left-join

我有以下 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.STATEns.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/

相关文章:

mysql - 从多对多关系的末端选择数据

sql - OPENJSON 与 NULL 值交叉应用 (SQL)

sql - IntelliJ IDEA 13 SQL 语句高亮

php if 语句总是返回 false

Java分布式数据库数据共享

mysql - 需要一个 MySQL JOIN 来返回产品所属的所有类别,每个产品,即使只搜索一个类别

Mysql 将 varchar 视为 int 错误?

database - 将业务规则建模到数据库中

php - 获取返回的 PHP 结果数

mysql - SQL : Limit and Randomize results in join