【问题标题】:SQL query data join has null values that it ignoresSQL 查询数据连接具有它忽略的空值
【发布时间】:2012-05-15 19:56:47
【问题描述】:

我在 SQL Server 中有一个表,其中包含一个分类帐代码列,该分类帐代码通过 keyfield 链接到 ledgercode 表。目前该列显示keyfield 值而不是我使用此查询创建新表的代码号:

SELECT [OC_Key]
  ,[OC_PO_PO_DPNo]
  ,[OC_DateofInv]
  ,[V_VendorNo]
  ,[OC_ExpDescrip]
  ,[LedgerCode]
  ,[OC_InvoiceNo]
  ,[OC_DatePosted]
  ,[OC_TotAmount]
  ,[OC_Type]
  ,[OC_Initials]
INTO dbo.OCommittedTbl
FROM [CommittedTbl] CT, [codeLedgerTbl] LT, [VendorTbl] VT
WHERE VT.V_VenKey = CT.OC_VendorName and LT.LedgerKey = CT.OC_LedgerCode 

我遇到的问题是表中的某些行的 ledgercode 列的值为空,因此这个新表仅将 484 行中的 34 行拉入表中。

如何绕过空值,以便它们仍会被拉到我的表中?

【问题讨论】:

  • 你永远不应该编写隐式连接,它们是一种 sql 反模式,在 20 年前被更好的显式连接所取代。

标签: sql-server tsql select-into


【解决方案1】:

使用 LEFT JOIN 而不是(隐式)INNER JOIN。

SELECT ...
INTO dbo.OCommittedTbl
FROM [CommittedTbl] CT
LEFT JOIN [codeLedgerTbl] LT ON LT.LedgerKey = CT.OC_LedgerCode 
LEFT JOIN [VendorTbl] VT ON VT.V_VenKey = CT.OC_VendorName 

【讨论】:

    【解决方案2】:

    首先,您需要学习 JOIN 语法。其次,你的问题的答案是左外连接:

    SELECT [OC_Key], [OC_PO_PO_DPNo], [OC_DateofInv], [V_VendorNo], [OC_ExpDescrip],
           [LedgerCode], [OC_InvoiceNo], [OC_DatePosted], [OC_TotAmount], [OC_Type], [OC_Initials]
    INTO dbo.OCommittedTbl
    FROM [CommittedTbl] CT left outer join
         [codeLedgerTbl] LT
         on LT.LedgerKey = CT.OC_LedgerCode left outer join
         [VendorTbl] VT
          on VT.V_VenKey = CT.OC_VendorName
    

    第三,我非常喜欢同名的主键和外键。因此,如果您构建了原始表,那么您可能会使用一致的命名约定。

    【讨论】:

      【解决方案3】:

      INNER JOIN 排除空条目,尝试左连接

      SELECT [OC_Key]
        ,[OC_PO_PO_DPNo]
        ,[OC_DateofInv]
        ,[V_VendorNo]
        ,[OC_ExpDescrip]
        ,[LedgerCode]
        ,[OC_InvoiceNo]
        ,[OC_DatePosted]
        ,[OC_TotAmount]
        ,[OC_Type]
        ,[OC_Initials]
      INTO dbo.OCommittedTbl
      FROM [CommittedTbl] CT
      LEFT JOIN [codeLedgerTbl] LT ON LT.LedgerKey = CT.OC_LedgerCode 
      LEFT JOIN [VendorTbl] VT ON VT.V_VenKey = CT.OC_VendorName
      WHERE VT.V_VenKey = CT.OC_VendorName and LT.LedgerKey = CT.OC_LedgerCode 
      

      【讨论】:

        猜你喜欢
        • 2019-04-11
        • 1970-01-01
        • 1970-01-01
        • 2013-08-14
        • 1970-01-01
        • 1970-01-01
        • 2014-06-24
        • 1970-01-01
        • 2012-06-01
        相关资源
        最近更新 更多