如何在mysql中检索不匹配的结果

8 mysql database join

我确信这很简单,但是如何在mysql中编写一个连接两个表的查询,然后只返回第一个表中不匹配的记录.我希望它是这样的:

Select tid from table1 inner join table2 on table2.tid = table1.tid where table1.tid != table2.tid;

但这似乎没有多大意义!

Eri*_*ric 18

您可以使用a left outer join来完成此任务:

select
    t1.tid
from
    table1 t1
    left outer join table2 t2 on
        t1.tid = t2.tid
where
    t2.tid is null
Run Code Online (Sandbox Code Playgroud)

这样做是需要你的第一个表(table1),与你的第二个表(加入它table2),并填写nulltable2列在任何行中table1,在不匹配的行table2.然后,它通过仅选择table1无法找到匹配的行来过滤掉.

或者,您也可以使用not exists:

select
    t1.tid
from
    table1 t1
where
    not exists (select 1 from table2 t2 where t2.tid = t1.tid)
Run Code Online (Sandbox Code Playgroud)

这执行了一个left semi join,并且基本上会做同样的事情left outer join.根据您的索引,一个可能比另一个更快,但两者都是可行的选项.MySQL有一些关于优化连接的好文档,所以你应该检查一下..

  • @ musoNic80另请查看http://www.codinghorror.com/blog/archives/000976.html (2认同)