从两个表中获取唯一数据

时间:2015-07-03 09:31:49

标签: mysql sql join

我有两张桌子。 ProductA和ProductB。

产品A

+----+-------+
| ID | SubId |
+----+-------+
| A1 |  112  |
| B1 |  111  |
| C1 |  115  |
| D1 |  117  |
| E1 |  114  |
| F1 |  112  |
+----+-------+

产品B

+----+-------+
| ID | SubId |
+----+-------+
| A1 |  112  |
| B1 |  111  |
| C1 |  115  |
| G1 |  001  |
| H1 |  002  |
| k1 |  003  |
+----+-------+

我想编写一个查询,检索两列IDSubId,并显示ProductA表中不在ProductB的不同行。所以对于上面的表格。

预期结果

+----+-------+
| ID | SubId |
+----+-------+
| D1 |  117  |
| E1 |  114  |
| F1 |  112  |
+----+-------+

我怎样才能完成这项工作?

6 个答案:

答案 0 :(得分:1)

<强>查询

select distinct *
from productA
where not exists
(
  select null 
  from productB
  where productA.id = productB.id
  and productA.subid=productB.subid
);

Fiddle demo here

答案 1 :(得分:0)

尝试此查询

select * from ProductA where not EXISTS(select * from productb)

答案 2 :(得分:0)

更新

稍后24次修改!你现在怎么样我!

http://sqlfiddle.com/#!9/954792/24

SELECT
    foo.pid, 
    foo.sid from (
        SELECT 
            PA.`ID` as pid, 
            PA.`SubId` as sid 
        FROM 
            `ProductA` as PA
        LEFT JOIN 
            `ProductB` as PB
        ON 
            PA.`ID` = PB.`ID`
        WHERE 
            PB.`ID` is NULL

        UNION

        SELECT 
            P2A.`ID` as ppid, 
            P2A.`SubId` as ssid 
        FROM 
            `ProductA` as P2A
        RIGHT JOIN 
            `ProductB` as P2B
        ON 
            P2A.`ID` = P2B.`ID`
        WHERE 
            P2B.`ID` is NULL
   ) as foo

enter image description here

这是一个解释联接的好链接......

http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/

答案 3 :(得分:0)

SELECT <select_list>
FROM TableA A
FULL OUTER JOIN TableB B
ON A.Key==B.Key
WHERE A.Key is NULL OR B.Key IS NULL;

答案 4 :(得分:0)

select * from productA a 
left outer join productB b 
on a.ID = b.ID 
and a.subid=b.subid 
where b.subid is null 
and b.id is null;

答案 5 :(得分:0)

你应该尝试以下,

Select * from ProductA A
  Left Join ProductB B on A.ID = B.Id
Where B.Id is null or B.SubId is null

它会给你渴望的结果。