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

问题描述 投票:1回答:2

我有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

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

sql sql-server join
2个回答
3
投票

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

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 

4
投票

使用显式连接

  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
© www.soinside.com 2019 - 2024. All rights reserved.