简体   繁体   English

在两个表之间选择不常见的记录-MySQL

[英]select uncommon records between two tables - mysql

I have two tables, table A and table B with the same column names. 我有两个表,表A和表B具有相同的列名。 I want to fetch those records which are not present in table A but present in table B. 我想获取那些不在表A中但在表B中存在的记录。

Thanks in advance. 提前致谢。

使用左联接

Select * from tableb left join tablea on tableb.column = tablea.coulmn where tablea.column is null 

Some databases support except or minus . 某些数据库支持exceptminus But not MySQL. 但不是MySQL。 I would recommend not exists : 我建议not exists

select b.*
from b
where not exists (select 1
                  from a
                  where a.col1 = b.col1 and a.col2 = b.col2 and . . .
                 );

Note that this will not work if any columns have NULL values. 请注意,如果任何列具有NULL值,这将不起作用。

If you need to handle NULL s, you could use (not a.col1 <=> b.col1) and (not a.col2 <=> b.col2) . . . 如果需要处理NULL ,则可以使用(not a.col1 <=> b.col1) and (not a.col2 <=> b.col2) . . . (not a.col1 <=> b.col1) and (not a.col2 <=> b.col2) . . . . Or, you could use aggregation: 或者,您可以使用聚合:

select col1, col2, . . .
from ((select a.*, 1 as is_a, 0 as is_b
       from a
      ) union all
      (select b.*, 0, 1
       from b
      ) 
     ) ab
group by col1, col2, . . .
having max(is_a) = 0 and max(is_b) = 1;

Suppose the rows are same if their primary keys are same (for example, id field). 如果行的主键相同(例如,id字段),则假定行相同。 Than you can: 比您可以:

select id from b where id not in (select id from a)

If your tables has no primary keys or they do not match - you can alter the query to your tables structure. 如果表没有主键或它们不匹配-您可以将查询更改为表结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM