sql server - 连接空值

时间:2011-06-01 08:53:06

标签: sql sql-server tsql sql-server-2008 left-join

我有两张桌子。一个包含链接列表,另一个包含其样式(如果可用)。 后者是稀疏表,即当它们的值为null时它没有相应的行。 我运行以下查询:

select hl.*, hls.colorCode, hls.bold
from HeaderLinks hl, HeaderLinkStyles hls 
where hl.LinkId = hls.linkID
order by row asc, [column] asc

我想修改它,以便如果特定记录不存在某行,这些列将在结果集中接收空值。

谢谢!

5 个答案:

答案 0 :(得分:4)

Left Join

Select hl.*, hls.colorCode, hls.bold 
From HeaderLinks hl
Left Join HeaderLinkStyles hls on hl.LinkId = hls.linkID
order by row asc,[column] ASC

答案 1 :(得分:1)

要获取不存在记录的NULL,您需要在表格上使用LEFT OUTER JOIN或RIGHT OUTER JOIN .......

Select hl.*, hls.colorCode, hls.bold From HeaderLinks hl
Left Join HeaderLinkStyles hls on hl.LinkId = hls.linkID order by row asc,[column] ASC

enter image description here

点击此处加入:Visual Representation of SQL Joins

答案 2 :(得分:1)

当找不到匹配项时,leftfull联接将填充null行:

select  *
from    HeaderLinks hl
full outer join
        HeaderLinkStyles hls 
on      hl.LinkId = hls.linkID 

左连接仅使用空值填充右侧表,右侧连接仅填充左侧表,完全连接填充两者。有关视觉说明,请参阅A Visual Explanation of SQL Joins

答案 3 :(得分:0)

您需要使用左外连接

select hl.*, hls.colorCode, hls.bold
from HeaderLinks hl
    left join HeaderLinkStyles hls on
      hl.LinkId = hls.linkID  
order by row asc, [column] asc

Using Outer Joins

答案 4 :(得分:0)

您需要使用LEFT JOIN

Select 
  hl.*, 
  hls.colorCode, 
  hls.bold 
from 
  HeaderLinks hl 
LEFT JOIN 
  HeaderLinkStyles hls on hl.LinkId = hls.linkID
order by 
  row asc,[column] ASC