【问题标题】:mysql compare two tables to find not matched recordsmysql比较两个表找到不匹配的记录
【发布时间】:2016-11-17 12:36:48
【问题描述】:

查看这两个示例表:

表 1:

id   FN LN  电子邮件

1 A B  C

2 D E E F

3 G H H I

表 2:

id   FN LN  电子邮件

1 A   Z   C

2 D          F

3 G  H  I

我想要来自 table1 的不相等的输出并且只显示更改一个。我尝试了很多方法,但没有结果。

输出:

id LN

---- ---

1 Z

【问题讨论】:

  • 如果 3 G 更改为 3 K,您的预期输出将如何? (包括更改为 1)

标签: mysql database codeigniter


【解决方案1】:
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 

结果

+------+--------------+----------------+
| id   | FieldChanged | FieldChangedTo |
+------+--------------+----------------+
|    1 | LN           | Z              |
|    3 | FN           | k              |
+------+--------------+----------------+
2 rows in set (0.00 sec)

【讨论】:

    【解决方案2】:

    如果您希望该 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
    

    【讨论】:

    • 我已经绑定了你的方法得到不准确的结果,但是 P.salmon 工作正常,因为我想要它。无论如何感谢@quantummind :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 1970-01-01
    相关资源
    最近更新 更多