我的查询结果集大约是6万行:
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
为什么我的左手会加入LIMIT我的结果集?
答案 0 :(得分:4)
您不仅要添加左外连接,还要添加过滤条件:
and d.REC_ACTIVE_FLG=1
and s.REC_ACTIVE_FLG=1
这有效地将您的外连接转换为内连接。它还可能过滤掉d
和/或s
存在的一些记录,但REC_ACTIVE_FLG
不等于1
。
答案 1 :(得分: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