简体   繁体   English

2个SQL表之间的区别

[英]Difference between 2 SQL tables

I have two tables: tableA and tableB. 我有两个表:tableA和tableB。 How can I get all the records that are in tableA but not in tableB? 如何获取tableA中的所有记录,但不能获取tableB中的所有记录? I am interested in the proper way to do this, not workarounds. 我对正确的方法感兴趣,而不是解决方法。 I've tried using a left join and then adding where ID is not null . 我尝试过使用左连接,然后添加where ID is not null It works, but I am not sure whether that is the right way to do it. 它有效,但我不确定这是否是正确的方法。

select * from tableA
where id not in (select id from tableB)

or 要么

select * from tableA a
left join tableB b on a.id = b.id
where b.id is null

Both are totally acceptable ways to retrieve what you asked. 两者都是完全可以接受的方式来检索您的要求。

You have to use join for this if you need to show the data on the page (programming), in case you need to move your data from one table to another table for backup or other similar purpose, you need a sql compare tool. 如果需要在页面上显示数据(编程),则必须使用join,如果需要将数据从一个表移动到另一个表以进行备份或其他类似目的,则需要使用sql compare工具。 For first on you need sql left join. 首先你需要sql left join。 Make your table A as left one and put and join with B 将您的桌子A作为左边的一个,然后放入并与B一起加入

select * from A
left join B  on A.id = B.id
where b.id is null

You can use NOT EXISTS . 您可以使用NOT EXISTS I prefer to use NOT EXISTS because when the columns allow nulls but has none, the NOT IN performs significantly worse than NOT EXISTS . 我更喜欢使用NOT EXISTS因为当列允许空值但没有时, NOT IN表现明显比NOT EXISTS差。

Select * from table1 a
    Where not exists (Select ID from table2 b where a.ID = b.ID)

On non-nullable columns, you can use either of them which fits to your situation as the behaviour and performance of NOT IN and NOT EXISTS are the same. non-nullable列上,您可以使用适合您情况的任一列,因为NOT IN和NOT EXISTS的行为和性能是相同的。

Sql fiddle [][1] Sql小提琴[] [1]

Demo http://www.sqlfiddle.com/#!3/10300/2 演示 http://www.sqlfiddle.com/#!3/10300/2

select * from table1 where id not in(select id from table2)

Since you have not given the table schema lets assume that there are primary key in each table.id1,id2 由于您没有给出表模式,因此假设每个table.id1,id2中都有主键

YOU Can do with the help of left join. 您可以在左连接的帮助下完成。

Select * from table1 left join table2 where id2 is null 选择* from table1 left join table2,其中id2为null

NOte this is not an actual query just a hint for you to go ahead. 这不是一个实际的查询,只是提示你继续。

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

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