在SQL Server联接中显示NULL值

时间:2011-10-07 09:03:39

标签: sql-server tsql join

我正在使用SQL Server。我有3张桌子:

  1. tblUser
  2. tblAudit
  3. tblEnum
  4. tblAudit有4列:

    nUserId,nID:这两列指向tblUser

    vFromValue,vToValue:这两列指向tblEnum

    现在,我需要根据tblAudit表中的ID显示tblUser和tblEnum中的实际值。 我写的查询看起来像这样:

    SELECT A.aEventID,
    U.tName AS MakerChecker,
    U2.tName AS OnUser,
    VLE.tDisplayName AS FromValue,
    VLE2.tDisplayName AS ToValue,
    A.dChangeTime AS Timestamp
    FROM tblAudit A INNER JOIN tblUser U ON A.nUserId = U.aUserId
    INNER JOIN tblUser U2 ON A.nID = U2.aUserId
    INNER JOIN tblEnum VLE ON A.vFromValue = VLE.nIndex OR (A.vFromValue IS NULL)
    INNER JOIN tblEnum VLE2 ON  A.vToValue = VLE2.nIndex OR (A.vToValue IS NULL)
    

    因为对于某些行,Audit表中的值对于列vFromValue和vToValue为空,所以这些值不是NULL,而是前一个值。 如何通过更改上述查询来完整显示空值?请帮忙。

2 个答案:

答案 0 :(得分:0)

如果我理解你的问题 - 尝试对你的最后两行使用LEFT JOIN(并删除OR之后的条件)。

答案 1 :(得分:0)

由于tblAudit.vFromValuetblAudit.vToValueNULL,请尝试以下操作:

SELECT A.aEventID,
       U.tName AS MakerChecker,
       U2.tName AS OnUser,
       VLE.tDisplayName AS FromValue,
       VLE2.tDisplayName AS ToValue,
       A.dChangeTime AS Timestamp
FROM 
     ( SELECT aEventID, nUserId, nID, dChangeTime  
            , COALESCE(vFromValue, -9999) AS vFromValue   --- some non-existent
            , COALESCE(vToValue, -999) AS vToValue        --- value
       FROM tblAudit
     ) AS A 
  INNER JOIN tblUser U
    ON A.nUserId = U.aUserId
  INNER JOIN tblUser U2 
    ON A.nID = U2.aUserId
  LEFT JOIN tblEnum VLE 
    ON A.vFromValue = VLE.nIndex
  LEFT JOIN tblEnum VLE2 
    ON  A.vToValue = VLE2.nIndex

或者这个:

SELECT A.aEventID,
       U.tName AS MakerChecker,
       U2.tName AS OnUser,
       ( SELECT VLE.tDisplayName
         FROM tblEnum VLE 
         WHERE A.vFromValue = VLE.nIndex
       ) AS FromValue,
       ( SELECT VLE2.tDisplayName
         FROM tblEnum VLE2 
         WHERE A.vToValue = VLE.nIndex
       ) AS ToValue,
       A.dChangeTime AS Timestamp
FROM tblAudit AS A 
  INNER JOIN tblUser U
    ON A.nUserId = U.aUserId
  INNER JOIN tblUser U2 
    ON A.nID = U2.aUserId