你的SELECT語句
Select CDR.*,
p1.*,
p2.*,
p3.*
From dbo.T_CDR_APPEL CDR
Inner Join dbo.POS As p1 On CDR.CDR_LOC_CODE = p1.Loc_Code And
CDR.CDR_LOC_CODE Like 'SC%VI%' And CDR.CDR_TYPE Like 'I%'
Inner Join dbo.POS As p2 On CDR.CDR_LAST_REDIR_NO = p2.Post_type And
CDR.CDR_LOC_CODE Like 'CCN%' And CDR.CDR_TYPE Like 'I'
Inner Join dbo.POS As p3 On CDR.CDR_LAST_REDIR_NO = p3.Backup_Number And
CDR.CDR_LOC_CODE Like 'VoiceMail%' And CDR.CDR_TYPE Like 'IF'
是基本相同
SELECT CDR.*,
p1.*,
p2.*,
p3.*
FROM dbo.T_CDR_APPEL CDR
INNER JOIN dbo.POS AS p1 ON CDR.CDR_LOC_CODE = p1.Loc_Code
INNER JOIN dbo.POS AS p2 ON CDR.CDR_LAST_REDIR_NO = p2.Post_type
INNER JOIN dbo.POS AS p3 ON CDR.CDR_LAST_REDIR_NO = p3.Backup_Number
WHERE
CDR.CDR_LOC_CODE LIKE 'SC%VI%' AND
CDR.CDR_LOC_CODE LIKE 'CCN%' AND
CDR.CDR_LOC_CODE LIKE 'VoiceMail%' AND
CDR.CDR_TYPE LIKE 'I%' AND
CDR.CDR_TYPE LIKE 'I' AND
CDR.CDR_TYPE LIKE 'IF'
因此,問題是WHERE
子句與CDR.CDR_LOC_CODE
和CDR.CDR_TYPE
相同的列的AND
條件的許多組合。請嘗試用OR
代替AND
。
更新: 由於p1,p2,p3
是相同的表,避免重複列,試試這個
SELECT CDR.*, p.* FROM
(
SELECT *,
(CASE
WHEN CDR_TYPE LIKE 'I%' THEN CDR_LOC_CODE
WHEN CDR_TYPE LIKE 'I' THEN CDR_LAST_REDIR_NO
WHEN CDR_TYPE LIKE 'IF' THEN CDR_LAST_REDIR_NO
ELSE ''
END) TMP_COL FROM dbo.T_CDR_APPEL
) CDR
INNER JOIN dbo.POS p ON
(CASE
WHEN CDR.CDR_TYPE LIKE 'I%' THEN p.Loc_Code
WHEN CDR.CDR_TYPE LIKE 'I' THEN p.Post_type
WHEN CDR.CDR_TYPE LIKE 'IF' THEN p.Backup_Number
ELSE ''
END) = CDR.TMP_COL
WHERE
(CDR.CDR_LOC_CODE LIKE 'SC%VI%' AND CDR.CDR_TYPE LIKE 'I%') OR
(CDR.CDR_LOC_CODE LIKE 'CCN%' AND CDR.CDR_TYPE LIKE 'I') OR
(CDR.CDR_LOC_CODE LIKE 'VoiceMail%' AND CDR.CDR_TYPE LIKE 'IF')
注:運行上述查詢可能需要一段時間與大表。您可能需要爲WHERE
子句添加一些條件以進一步調整。我們還應該把WHERE
子句放到子查詢中,因爲CDR_LOC_CODE
和CDR_TYPE
與dbo.T_CDR_APPEL
是同一個表。另外,請檢查動態列TMP_COL
的空值或空值,以避免連接表ON '' = ''
或ON NULL = NULL
。
SELECT CDR.*, p.* FROM
(
SELECT *,
(CASE
WHEN CDR_TYPE LIKE 'I%' THEN CDR_LOC_CODE
WHEN CDR_TYPE LIKE 'I' THEN CDR_LAST_REDIR_NO
WHEN CDR_TYPE LIKE 'IF' THEN CDR_LAST_REDIR_NO
ELSE ''
END) TMP_COL FROM dbo.T_CDR_APPEL
WHERE
(CDR_LOC_CODE LIKE 'SC%VI%' AND CDR_TYPE LIKE 'I%') OR
(CDR_LOC_CODE LIKE 'CCN%' AND CDR_TYPE LIKE 'I') OR
(CDR_LOC_CODE LIKE 'VoiceMail%' AND CDR_TYPE LIKE 'IF')
) CDR
INNER JOIN dbo.POS p ON
(CASE
WHEN CDR.CDR_TYPE LIKE 'I%' THEN p.Loc_Code
WHEN CDR.CDR_TYPE LIKE 'I' THEN p.Post_type
WHEN CDR.CDR_TYPE LIKE 'IF' THEN p.Backup_Number
ELSE ''
END) = CDR.TMP_COL AND NULLIF(CDR.TMP_COL, '') IS NOT NULL
分步實施。從簡單的1表選擇開始。如果它按預期工作,請添加第一個連接。如果有效,請添加另一個連接等。 – jarlh
順便說一句,沒有通配符的「LIKE」通常可以用'='替換。 – jarlh
它與第一個Inner Join一起工作......但隨後第二個不工作 – Alexandre