SQL查询帮助需要包含不匹配的记录

时间:2013-02-15 16:24:01

标签: sql

我需要显示一个查询,该查询显示与主查找表匹配和不匹配的行

@PostCodes表包含主表的邮政编码,第二个查询将与之匹配

DECLARE @PostCodes TABLE 
(
    RowID int not null primary key identity(1,1), 
    Postcodes varchar(100) 
) 


SELECT 
   C.CampaignId, C.Name, C.Description,C.EndedOn, C.Active, C.Manager, 
   P.PostcodeArea, P.PostcodeDistrict
FROM 
   Campaign C, CampaignPostcode P, @PostCodes pc
WHERE 
   P.CampaignId = C.CampaignId AND
   P.PostcodeDistrict = pc.Postcodes AND
   C.EndedOn IS NULL 

第二个查询只返回匹配邮政编码的匹配记录,我已尝试将所有内容都包含在不匹配的记录中,但没有运气。

任何帮助?


编辑(表格)

 PostCodes  (table1)             Campaign (table2)                      

Id      Postcodes          CampaignId    Name      Desc           
1        AA                  1            camp1    Desc1
2        AB                  2            camp2    Desc2 
3        AC                  3            camp3    Desc3
4        AD                  4            camp4    Desc4

CampaignPostcode (table3)

CampaignPostcodeId  CampaignId  PostcodeArea
 1                      1          AA
 2                      2          AB
 3                      2          AB
 4                      3          AC

需要输出

   Id  CampaignName   Desc   PostcodeIn PostcodeOut
    1    Camp1        Desc1     AA          NULL
    2    Camp2        Desc2     AB          NULL
    3    Camp2        Desc2     AB          NULL
    4    Camp3        Desc3     AC          NULL
    5    Camp4        Desc4     NULL        AD

2 个答案:

答案 0 :(得分:1)

这个怎么样:

SELECT 
   C.CampaignId, C.Name, C.Description,C.EndedOn, C.Active, C.Manager, 
   P.PostcodeArea, P.PostcodeDistrict
FROM 
   Campaign C
INNER JOIN
   CampaignPostcode P ON P.CampaignId = C.CampaignId
LEFT OUTER JOIN
   @PostCodes pc ON P.PostcodeDistrict = pc.Postcodes 
WHERE 
   C.EndedOn IS NULL 

答案 1 :(得分:0)

请改为尝试:

SELECT   
  p.*
FROM @PostCodes AS PC
LEFT JOIN
(
  SELECT *
  FROM Campaign C
  INNER JOIN CampaignPostcode P ON  P.CampaignId = C.CampaignId
) AS p ON P.PostcodeDistrict = pc.Postcodes
WHERE P.EndedOn IS NULL