我如何在MS SQL中执行此条件连接?

时间:2013-01-09 07:36:06

标签: sql sql-server tsql join

我四处寻找条件连接,但似乎他们正在尝试做一些与我正在尝试的不同的事情。我会针对这个问题简化一下这个问题。

我有三张桌子:Users, Clients, and Employees.

Users表有两列,AssociatedID and UserType.

UserType"Client""Employee,"AssociatedID是客户端或员工表中的相应ID。

问题是,客户端和员工都使用ID的整数,因此每个表可能具有完全不同的ID(与GUID相反,这可以避免此问题)。

我想要的是一个查询,它将查看Users中的一行,并说明UserType是否为Employee,然后是Employees表的ID上的JOIN AssociatedID,如果UserType是Client,则在Clients表的ID上加入AssocaitedID。因此,如果客户端和员工都有一个名称列,我可以获得每个用户的所有名称,无论他们是客户还是员工。我正在使用SQL Server 2008 R2,如果这在这里有所作为。

2 个答案:

答案 0 :(得分:8)

试试这个:

SELECT 
  COALESCE(c.Name, e.Name) AssociatedName,
  ... 
FROM Users u
LEFT JOIN Clients c    ON u.AssociatedID = c.ClientId
                      AND u.UserType     = 'Client'
LEFT JOIN Employees e  ON u.AssociatedID = e.EmployeeId
                      AND u.UserType     = 'Employee';

SQL Fiddle demo

或者:正如@Tikkes指出的那样,您可以使用UNION这样做:

SELECT c.Name AssociatedName
FROM Users u
INNER JOIN Clients c    ON u.AssociatedID = c.ClientId
                      AND u.UserType     = 'Client'
UNION ALL
SELECT e.Name FROM Users u
INNER JOIN Employees e  ON u.AssociatedID = e.EmployeeId
                      AND u.UserType     = 'Employee';

Updated SQL Fiddle Demo


更新:为此,您必须使用CASE这样的表达式:

SELECT 
  u.AssociatedID,
  CASE u.UserType 
   WHEN 'Client' THEN c.Name
   ELSE e.Name 
  END AS AssociationName
FROM Users u
LEFT JOIN Clients c    ON u.AssociatedID = c.ClientId      
LEFT JOIN Employees e  ON u.AssociatedID = e.EmployeeId;

Updated SQL Fiddle Demo using CASE

答案 1 :(得分:0)

相同的Senario:我有CustomerExt有SoldTo和ShipTo代码, 如果ShipTo列具有值,则在表ShipTo中使用ShipToName,否则在Customer表中使用CustomerName

Select COALESCE(B.CustomerName, C.ShiptoName) as CustomerName  
FROM CustomerExt A

left join Customer B    ON A.SoldTo = B.CustomerCode
                      AND isnull(A.ShipTo,'') =''

left join ShipTo C  ON A.ShipTo = C.ShipToCode
                      AND isnull(A.ShipTo,'') <>''