T-SQL外连接,多个表不起作用

时间:2017-03-06 17:37:45

标签: sql-server tsql

我正在尝试在MS SQL Server工具中编写查询,尽管我更习惯于Oracle SQL Developer。下面的查询运行,但它只返回第一个表的结果。我也试过使用LEFT JOIN而不是FULL OUTER JOIN,但我得到了相同的结果。我做错了什么?

SELECT c_s.FiscalYear, c_s.LeadMinistry, c_s.LogNo, c_s.MinRef, c_s.nl_Form
  FROM [cds].[dbo].[c_Submission] c_s
FULL OUTER JOIN [cds].[dbo].[c_AdminData] c_ad
ON c_s.LogNo = c_ad.LogNo
FULL OUTER JOIN [cds].[dbo].[c_Edited Key Comments] c_kc
ON c_s.LogNo = c_kc.LogNo
FULL OUTER JOIN [cds].[dbo].[c_Edited Minutes] c_min
ON c_s.LogNo = c_min.LogNo
FULL OUTER JOIN [cds].[dbo].[c_MB20BA] c_bn
ON c_s.LogNo = c_bn.LogNo
WHERE (c_s.LogNo IS NOT NULL)
ORDER BY c_s.LogNo;

2 个答案:

答案 0 :(得分:2)

如果要预先过滤第一个表,最好在子查询或CTE中执行此操作。如果你想要所有表的真正完全连接,你需要在Keys上使用COALESCE。否则它将成为LEFT联接。

;WITH _Submission AS 
(
    SELECT * FROM  [cds].[dbo].[c_Submission] c_s
    WHERE (c_s.LogNo IS NOT NULL)
)

SELECT c_s.FiscalYear, c_s.LeadMinistry,  COALESCE(c_s.LogNo, c_ad.LogNo, c_kc.LogNo, c_min.LogNo) AS LogNo, c_s.MinRef, c_s.nl_Form
FROM _Submission c_s
    FULL OUTER JOIN [cds].[dbo].[c_AdminData] c_ad
        ON c_s.LogNo = c_ad.LogNo
    FULL OUTER JOIN [cds].[dbo].[c_Edited Key Comments] c_kc
        ON COALESCE(c_s.LogNo, c_ad.LogNo)  = c_kc.LogNo
    FULL OUTER JOIN [cds].[dbo].[c_Edited Minutes] c_min
        ON COALESCE(c_s.LogNo, c_ad.LogNo, c_kc.LogNo) = c_min.LogNo
    FULL OUTER JOIN [cds].[dbo].[c_MB20BA] c_bn
        ON  COALESCE(c_s.LogNo, c_ad.LogNo, c_kc.LogNo, c_min.LogNo)  = c_bn.LogNo
ORDER BY LogNo;

答案 1 :(得分:1)

Where中的条件应该在ON子句中,否则完整联接将变为单边联接:

select c_s.FiscalYear,
    c_s.LeadMinistry,
    c_s.LogNo,      -- Use coalesce to get non null LogNo from the join
    c_s.MinRef,
    c_s.nl_Form
from [cds].[dbo].[c_Submission] c_s
full outer join [cds].[dbo].[c_AdminData] c_ad
    on c_s.LogNo = c_ad.LogNo
full outer join [cds].[dbo].[c_Edited Key Comments] c_kc
    on c_s.LogNo = c_kc.LogNo
full outer join [cds].[dbo].[c_Edited Minutes] c_min
    on c_s.LogNo = c_min.LogNo
full outer join [cds].[dbo].[c_MB20BA] c_bn
    on c_s.LogNo = c_bn.LogNo
        and c_s.LogNo is not null
order by c_s.LogNo

您可以使用coalesce来获取非null LogNo:

COALESCE(c_s.LogNo, c_ad.LogNo, c_kc.LogNo, c_min.LogNo)