SQL Server:JOIN返回部分数据

时间:2016-01-12 18:17:55

标签: sql-server sql-server-2008 join

我正在加入4张桌子但是在加入过程中我只回来了我回来的902行中的45个电话号码。我知道这是无效的,并且应该包含至少500行左右的电话。在我的加入中,我遗漏了一些非常简单的东西,我似乎无法识别。任何帮助表示赞赏。谢谢!

这是我的问题:

SELECT 
    CUST.ACCOUNTNUM,
    PARTYTABLE.NAME,
    '' AS 'LEGAL NAME',
    --replace(replace(DIRPARTYPOSTALADDRESSVIEW.ADDRESS, char(13), ' '), char(10), ' ') AS 'ADDRESS',
    '' AS 'ADDRESS 2',
    '' AS 'ADDRESS 3',
    LOGISTICSADDRESS.STREET,
    LOGISTICSADDRESS.CITY,
    LOGISTICSADDRESS.STATE,
    LOGISTICSADDRESS.COUNTY,
    LOGISTICSADDRESS.ZIPCODE,
    LOGISTICSADDRESS.COUNTRYREGIONID AS 'COUNTRY',
      CASE
        WHEN electronicaddress.type = 1
        THEN electronicaddress.locator
        ELSE 'NULL'
        END AS 'Phone',
     CASE 
        WHEN electronicaddress.type = 4
        THEN electronicaddress.locator
        ELSE 'NULL'
        END AS 'Fax',
     CASE WHEN electronicaddress.type = 20
        THEN electronicaddress.locator
        ELSE 'NULL'
        END AS 'Email',
    CUST.SALESGROUP AS 'BROKER NAME',
    '' AS 'DISTRIBUTOR'
FROM 
    CUSTTABLE CUST
LEFT JOIN 
    DIRPARTYTABLE AS PARTYTABLE ON CUST.PARTY = PARTYTABLE.RECID
LEFT JOIN 
    DIRPARTYPOSTALADDRESSVIEW AS POSTALADDRESS ON PARTYTABLE.RECID = POSTALADDRESS.PARTY
LEFT JOIN 
    LOGISTICSPOSTALADDRESS AS LOGISTICSADDRESS ON LOGISTICSADDRESS.PRIVATEFORPARTY = PARTYTABLE.RECID 
LEFT JOIN 
    LOGISTICSELECTRONICADDRESS AS ELECTRONICADDRESS ON PARTYTABLE.RECID = ELECTRONICADDRESS.PRIVATEFORPARTY
-- modify below to show NOT LIKE (not like '%A/P' go get all ship-to) or LIKE (contains '%A/P%' to get bill-to)
WHERE 
    PARTYTABLE.NAME NOT LIKE '%A/P%'
ORDER BY 
    CUST.ACCOUNTNUM

2 个答案:

答案 0 :(得分:1)

将过滤器移至ON条件。这隐含地将您的LEFT OUTER JOIN转换为INNER JOIN

........
LEFT JOIN DIRPARTYTABLE AS PARTYTABLE 
       ON CUST.PARTY = PARTYTABLE.RECID
      AND PARTYTABLE.NAME NOT LIKE '%A/P%'
........

答案 1 :(得分:0)

试试这个:

FROM CUSTTABLE CUST
    LEFT JOIN DIRPARTYTABLE AS PARTYTABLE ON CUST.PARTY = PARTYTABLE.RECID
         AND PARTYTABLE.NAME NOT LIKE '%A/P%'
    LEFT JOIN DIRPARTYPOSTALADDRESSVIEW AS POSTALADDRESS ON PARTYTABLE.RECID = POSTALADDRESS.PARTY
    LEFT JOIN LOGISTICSPOSTALADDRESS AS LOGISTICSADDRESS ON LOGISTICSADDRESS.PRIVATEFORPARTY = PARTYTABLE.RECID 
    LEFT JOIN LOGISTICSELECTRONICADDRESS AS ELECTRONICADDRESS ON PARTYTABLE.RECID = ELECTRONICADDRESS.PRIVATEFORPARTY
-- modify below to show NOT LIKE (not like '%A/P' go get all ship-to) or LIKE (contains '%A/P%' to get bill-to)