在树表上包含对INNER JOIN SQL Server查询具有空值的记录

时间:2015-05-21 14:27:10

标签: sql-server sql-server-2008 join nested-table

我正在查询一个嵌套了对自身的引用的表,并且我需要获取记录在我正在使用的INNER JOIN值上有一个空引用。换句话说,树表记录可能达不到相同的深度,我需要获得所有这些记录。

我正在使用的查询是:

$query = mysql_query("select * from login where password='$password' AND username LIKE '%$username%'", $connection) or die(mysql_error());

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

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>

1 个答案:

答案 0 :(得分:2)

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)。