从三个表中选择数据,包括空值

时间:2019-04-10 08:47:51

标签: sql sql-server join

我有3张桌子:

1. tbl_Country(CountryID,CountryName)
2. tbl_Customer(CustumerID,Name,CountryID,StateID)
3. tbl_State(StateID,StateName,CountryID)

我正在尝试使用以下查询联接这些表:

select cu.CustID,
       cu.CountryID,
       cu.StateID,
       cu.Name,
       c.CountryName,
       s.StateName 
from tbl_Customer cu, 
     tbl_Country c,
     tbl_State s 
where c.CountryID = cu.CountryID and 
       s.StateID = cu.StateID and 
       c.CountryID = s.CountryID

但是我无法获取未指定国家名称或州名称的客户。我不知道如何编写完整的外部联接查询。

2 个答案:

答案 0 :(得分:5)

使用显式连接

  select cu.CustID,
           cu.CountryID,
           cu.StateID,
           cu.Name,
           c.CountryName,
           s.StateName  
    from tbl_Customer cu left join
         tbl_Country c on   c.CountryID = cu.CountryID
         left join tbl_State s   s.StateID = cu.StateID
         and c.CountryID = s.CountryID

答案 1 :(得分:4)

您需要使用左联接。如果客户是您的主表,请从该表开始查询。

SELECT cu.CustID, 
       cu.CountryID, 
       cu.StateID, 
       cu.Name, 
       c.CountryName, 
       s.StateName 
FROM   tbl_Customer cu 
       LEFT JOIN tbl_Country c 
              ON cu.CountryId = c.CountryId 
       LEFT JOIN tbl_State s 
              ON s.StateID = cu.StateID 
                 AND c.CountryID = s.CountryID