Join two tables to get matching records and unmatched records from Table 1

旧时模样 提交于 2019-12-12 05:11:29

问题


Scenario: I have 2 tables namely Coverage and Product

Coverage Table: CId,CName,CType,CMessage,CDate,CoverageProductId

Product Table: PId,CName,CType,CMessage,PDate,CoverageProductId

By using CoverageProductId i am relating 2 tables.

I need to get 3 columns CName,CMessage and CoverageProductId from both tables

Condition Below,

  • Get 3 columns values from Product table if both table CoverageProductId matches.
  • Get 3 columns values from Coverage table if both table CoverageProductId not matches.

My query is below in MS sql server

SELECT Distinct C.CoverageProductID
,C.CName
,C.CType
FROM Coverage C
INNER JOIN Product P
ON C.CoverageProductID!=P.CoverageProductID
UNION
SELECT Distinct P.CoverageProductID
,P.CName
,P.CType
FROM Coverage C
INNER JOIN Product P
ON C.CoverageProductID=P.CoverageProductID

But the result is not as expected and it returns duplicate values.


回答1:


I think this might do what you want:

select P.CoverageProductID, P.CName, P.CType
from Product P
where exists (select 1
              from coverage c
              where p.CoverageProductID = c.CoverageProductID)
union all
select C.CoverageProductID, C.CName, C.CType
from Coverage C
where not exists (select 1
                  from product p
                  where p.CoverageProductID = c.CoverageProductID);

It gets all rows from Product that match in Coverage and then all rows from Coverage that don't have a match in Product.




回答2:


I have tried little better way for same query,

Below is my code,

SELECT 
ISNULL(P.CoverageProductID,C.CoverageProductID),
ISNULL(P.CType,C.CType)
ISNULL(P.CName,C.CName)
FROM   Coverage AS C
           LEFT OUTER JOIN
           Product AS P
           ON C.CoverageProductID = P.CoverageProductID


来源:https://stackoverflow.com/questions/31737341/join-two-tables-to-get-matching-records-and-unmatched-records-from-table-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!