根据2个表提取数据,其中1个或多个字段上的记录不匹配

时间:2019-07-01 14:09:50

标签: mysql sql

我现在正尝试从2个不同的表中提取数据,这些数据与1个或多个字段中的同一记录不匹配

TABLE 1
----------------------------------
ID          NAME            MEMBER          SMS_MEMBER
1           JOHN            YES             NO
2           JOY             'NO'            NO
3           SMITH           NO              'YES'
4           ANDRES          YES             YES
5           JIMMY           NO              YES


TABLE 2
----------------------------------
ID          NAME            MEMBER          SMS_MEMBER
1           JOHN            YES             NO
2           JOY             'YES'           NO
3           SMITH           NO             'NO'
4           ANDRES          YES             YES
5           JIMMY           NO              YES

这是我的逻辑查询

SELECT * FROM TABLE1
WHERE 
TABLE1.ID NOT IN TABLE2.ID 
OR
TABLE1.NAME NOT IN TABLE2.NAME 
OR
TABLE1.EMAIL_MEMBER NOT IN TABLE2.EMAIL_MEMBER
OR
TABLE1.SMS_MEMBER NOT IN TABLE2.SMS_MEMBER;

提取的记录将是

----------------------------------
ID          NAME            MEMBER          SMS_MEMBER
2           JOY             'NO'            NO
3           SMITH           NO              'YES'

由于以下记录匹配,因此将在查询后从最终摘录中排除

独家记录

ID          NAME            MEMBER          SMS_MEMBER
1           JOHN            YES             NO
4           ANDRES          YES             YES
5           JIMMY           NO              YES

如果你们也能帮助我,那太好了。

2 个答案:

答案 0 :(得分:2)

一种简单的方法使用聚合。假设在任何一个表中没有重复项:

select id, name, member, sms_member
from ((select id, name, member, sms_member
       from table1
      ) union all
      (select id, name, member, sms_member
       from table2
      )
     ) t
group by id, name, member, sms_member
having count(*) = 1;

但是,您的样本数据表明您只希望table2中的行不在table1中。如果是这样,我建议not exists

select t2.*
from table2 t2
where not exists (select 1
                  from table1 t1
                  where t1.id = t2.id and t1.name = t2.name and t1.member = t2.member an t1.sms_member = t2.sms_member
                 );

如果在任何列中可能有NULL值,则需要调整逻辑。

答案 1 :(得分:0)

您需要一个left join

select t1.*
from table1 t1 left join table2 t2
on t2.id = t1.id and t2.name = t1.name and t2.email_member = t1.email_member and t2.sms_member = t1.sms_member
where t2.id is null

匹配记录将被排除,因为对于它们来说t2.id不是null
请参见demo
结果:

| id  | name  | email_member | sms_member |
| --- | ----- | ------------ | ---------- |
| 2   | JOY   | NO           | NO         |
| 3   | SMITH | NO           | YES        |