包括在 INNER JOIN SQL 树上的服务器查询中具有空值的记录 table

Include records that has a null value on INNER JOIN SQL Server query over a tree table

我正在查询对自身有嵌套引用的 table,我需要获取对我正在使用的 INNER JOIN 值有空引用的记录。换句话说,树 table 记录可能没有达到相同的深度,我需要得到所有的记录。

我正在使用 atm 的查询是:

SELECT DISTINCT <valuesThatINeed>
FROM atable foo
   INNER JOIN treetable bar ON foo.id_bar = bar.id
   INNER JOIN treetable bar2 ON bar.id_bar = bar2.id
   INNER JOIN treetable bar3 ON bar2.id_bar = bar3.id
WHERE
   <constraints>

我读到我可以通过添加一个 OR 语句询问 bar.id_bar 是否为 NULL 来扩展 INNER JOIN 条件,但是如果我这样做我就无法达到更高的水平:

SELECT DISTINCT <valuesThatINeed>
FROM atable foo
   INNER JOIN treetable bar ON foo.id_bar = bar.id 
   INNER JOIN treetable bar2 ON bar.id_bar = bar2.id OR (bar.id_bar IS NULL) 
   INNER JOIN treetable bar3 ON bar2.id_bar = bar3.id
WHERE
   <constraints>

INNER JOIN 更改为 LEFT JOIN:

SELECT DISTINCT <valuesThatINeed>
, CASE 
     WHEN barN.id IS NULL 
         THEN 'Your previous level with BarID = ' 
               + CAST(barN-1.id AS NVARCHAR(MAX)) 
               + ' is the deepest level'
      ELSE ''
  END
FROM atable foo
   LEFT JOIN treetable bar ON foo.id_bar = bar.id 
   LEFT JOIN treetable bar2 ON bar.id_bar = bar2.id OR (bar.id_bar IS NULL) 
   LEFT JOIN treetable bar3 ON bar2.id_bar = bar3.id
   ...
   LEFT JOIN treetable barN ON barN-1.id_bar = barN.id
WHERE
   <constraints>

您可以继续进行 LEFT 连接,直到达到 barN.id IS NULL 的深度,这意味着您已达到 N-1 的最深层次。

但是,如果您尝试建立层次结构,那么这不是可扩展的方式。在网络上搜索递归 CTE (here is a possible hint which you can try to adapt to your situation)。


.