mysql比较两个表来查找不匹配的记录

时间:2016-11-17 12:36:49

标签: mysql database codeigniter

请参阅以下两个示例表:

表1:

id FN LN电子邮件

1 A B C

2 D E F

3 G H I

表2:

id FN LN电子邮件

1 A Z C

2 D E F

3 G H I

我希望输出与table1不相等,只显示更改一个。我尝试了很多方法但没有结果。

输出:

id LN

---- ---

1 Z

2 个答案:

答案 0 :(得分:0)

如果您希望该ID相同且任何其他列不同,您应该这样做:

select * from table1
join table2 on table1.id = table2.id
where table1.firstname != table2.firstname or
      table1.middlename != table2.middlename or 
      table1.lastname != table2.lastname

答案 1 :(得分:0)

\.

结果

drop table if exists t1;
create table t1(id int,  FN varchar(1), LN varchar(1), Email varchar(1));
insert into t1 values
(1 ,  'A',   'B',     'C'),
(2 ,  'D' ,  'E',     'F'),
(3 ,  'G' ,  'H',     'I');

drop table if exists t2;
create table t2(id int,  FN varchar(1), LN varchar(1), Email varchar(1));
insert into t2 values
(1 ,  'A',   'Z',     'C'),
(2 ,  'D' ,  'E',     'F'),
(3 ,  'k' ,  'H',     'l');

select t1.id,
        case when t1.fn <> t2.fn then 'FN'
        when t1.ln <> t2.ln then 'LN'
        when t1.email <> t2.email then 'email'
        END AS FieldChanged,
        case when t1.fn <> t2.fn then t2.fn
        when t1.ln <> t2.ln then t2.ln
        when t1.email <> t2.email then t2.email
        END AS FieldChangedTo

from t1
join t2 on t1.id = t2.id

where t1.fn <> t2.fn or
        t1.ln <> t2.ln or
        t1.email <> t2.email