在SELECT语句中引用COALESCED值的正确方法是什么?

时间:2011-03-14 20:36:51

标签: sql sql-server

如果我在SELECT语句中使用“COALESCE”函数。在JOIN中引用列值的正确方法是什么?例如..

SELECT 
  ID,
  COALESCE(TableA.Name1, TableA.Name2) 
FROM 
  TableA 
  LEFT JOIN TableB ON TableA.ID = TableB.ID 
  LEFT JOIN TableC ON TableA.ID = TableC.ID
  LEFT JOIN TableD ON <COALESCE VALUE HERE> = TableD.Name

5 个答案:

答案 0 :(得分:4)

您只需使用LEFT JOIN TableD ON COALESCE(TableA.Name1, TableA.Name2) = TableD.Name

无法在子句引用的查询中的任何位置引用SELECT子句中的表达式。

答案 1 :(得分:2)

这是扩展COALESCE的另一种方式,它可能在某些数据分发中效果更好

SELECT 
  ID,
  COALESCE(TableA.Name1, TableA.Name2) 
FROM 
  TableA 
  LEFT JOIN TableB ON TableA.ID = TableB.ID 
  LEFT JOIN TableC ON TableA.ID = TableC.ID
  LEFT JOIN TableD ON (TableA.Name1 = TableD.Name)
                   OR (TableA.Name1 IS NULL AND TableA.Name2 = TableD.Name)

答案 2 :(得分:1)

SELECT 
  ID,
  COALESCE(TableA.Name1, TableA.Name2) 
FROM 
  TableA 
  LEFT JOIN TableB ON TableA.ID = TableB.ID 
  LEFT JOIN TableC ON TableA.ID = TableC.ID
  LEFT JOIN TableD ON COALESCE(TableA.Name1, TableA.Name2) = TableD.Name

答案 3 :(得分:1)

对于其他人说的话,我会加上

SELECT Base.* FROM
    (SELECT 
        ID,
        COALESCE(TableA.Name1, TableA.Name2) Names
        FROM TableA
    ) Base

LEFT JOIN TableB ON Base.ID = TableB.ID 
LEFT JOIN TableC ON Base.ID = TableC.ID
LEFT JOIN TableD ON Base.Names = TableD.Name

正如Gabe建议的那样,CTE(我认为CTE在这里有点过分,我喜欢使用CTE)

; WITH Base AS (
    SELECT 
        ID,
        COALESCE(TableA.Name1, TableA.Name2) Names
        FROM TableA
)

SELECT Base.* From Base
    LEFT JOIN TableB ON Base.ID = TableB.ID 
    LEFT JOIN TableC ON Base.ID = TableC.ID
    LEFT JOIN TableD ON Base.Names = TableD.Name

答案 4 :(得分:0)

明显的方法可行:

LEFT JOIN 
        TableD 
ON      COALESCE(TableA.Name1, TableA.Name2) = TableD.Name

或:

LEFT JOIN 
        TableD 
ON      TableA.Name1 = TableD.Name
        OR TableA.Name2 = TableD.Name

(编辑:第二个查询不起作用,就像评论中所说的那样)