0

我的查询结果集大约是 60k 行:

SELECT f.client_id,
       f.SECTION_A,
       Month(f.received_date) Month,
       Count(*)               Count
FROM   MILLENNIUM_DW_DEV..F_ACCESSION_DAILY f
       LEFT JOIN salesdwh..TestPractices t
         ON F.CLIENT_ID = t.ClientID
WHERE  t.ClientID IS NULL
       AND Month(f.received_date) BETWEEN 1 AND 11
       AND Year(f.received_date) = 2012
GROUP  BY f.SECTION_A,
          Month(f.received_date),
          f.client_id 

但是,当我添加 2 个左连接时,它会将其限制为 56k 行!

SELECT f.client_id,
       f.SECTION_A,
       Month(f.received_date) Month,
       Count(*)               Count,
       s.SALES_REP_NAME,
       s.REGION_NAME
FROM   MILLENNIUM_DW_DEV..F_ACCESSION_DAILY f
       LEFT JOIN salesdwh..TestPractices t
         ON F.CLIENT_ID = t.ClientID
       LEFT JOIN MILLENNIUM_DW_DEV..D_CLIENT d
         ON d.CLIENT_ID = f.CLIENT_ID
       LEFT JOIN MILLENNIUM_DW_DEV..D_SALES_HIERARCHY s
         ON s.SUB_TERRITORY_NBR = d.SUB_TERRITORY_NBR
WHERE  t.ClientID IS NULL
       AND Month(f.received_date) BETWEEN 1 AND 11
       AND Year(f.received_date) = 2012
       AND d.REC_ACTIVE_FLG = 1
       AND s.REC_ACTIVE_FLG = 1
GROUP  BY f.SECTION_A,
          Month(f.received_date),
          f.client_id,
          s.SALES_REP_NAME,
          s.REGION_NAME 

为什么我的左连接会限制我的结果集?

4

2 回答 2

4

您不仅添加了左外连接,还添加了过滤条件:

and d.REC_ACTIVE_FLG=1
and s.REC_ACTIVE_FLG=1

这有效地将您的外部连接变成了内部连接。它还可能过滤掉一些存在d和/或s存在但REC_ACTIVE_FLG不等于的记录1

于 2012-12-11T20:24:56.750 回答
4

所以解决方法是将条件添加到on子句而不是where子句中:

FROM   MILLENNIUM_DW_DEV..F_ACCESSION_DAILY f
       LEFT JOIN salesdwh..TestPractices t
         ON F.CLIENT_ID = t.ClientID
       LEFT JOIN MILLENNIUM_DW_DEV..D_CLIENT d
         ON d.CLIENT_ID = f.CLIENT_ID and d.REC_ACTIVE_FLAG = 1
       LEFT JOIN MILLENNIUM_DW_DEV..D_SALES_HIERARCHY s
         ON s.SUB_TERRITORY_NBR = d.SUB_TERRITORY_NBR and s.REC_ACTIVE_FLAG = 1
于 2012-12-11T20:59:42.883 回答