0

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

@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
4

2 回答 2

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 
于 2013-02-15T16:29:09.423 回答
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 
于 2013-02-15T17:06:48.423 回答