在两个 mysql 表中查找不同行的最快方法
Fastest way to find different rows in two mysql tables
我有两个几乎相同的 table。第二个是第一个的 "slave"。第一个 table 有自动增量 int ID 列,第二个也有 ID2,它是索引唯一 int,但不是自动增量。 ID2 是 ID 的模拟。
我需要找到最快的方法来检测第二个 table 中的新行(第一个 table 中不存在的那些 ID2),反之亦然,第一个 table 中的新行(那些在第二 table 中不存在的 ID)。我发现最快的方法是
select SQL_NO_CACHE
tab1.ID
from `tab1`
left join `tab2`
on tab1.ID = tab2.ID2
where
isnull(tab2.ID2)
在约 20 万条记录上耗时 2.5 秒。您可以提出什么建议来获得更快的结果?
使用is null
:
select SQL_NO_CACHE tab1.ID
from `tab1` left join
`tab2`
on tab1.ID = tab2.ID2
where tab2.id2 is null;
此性能应相当于:
select tab1.id
from tab1
where not exists (select 1 from tab2 where tab2.id2 = tab.id);
但这两种方法都值得尝试。
请注意,这些版本与您的要求相反——查找 tab1
中不在 tab2
中的行。如何切换逻辑应该很明显,这取决于你真正想要什么。
SELECT * FROM Tab2 WHERE
NOT EXISTS (SELECT 'x' FROM Tab1 where
Tab1.ID= Tab2.ID)
我想这个查询会给你更快的结果。
我有两个几乎相同的 table。第二个是第一个的 "slave"。第一个 table 有自动增量 int ID 列,第二个也有 ID2,它是索引唯一 int,但不是自动增量。 ID2 是 ID 的模拟。
我需要找到最快的方法来检测第二个 table 中的新行(第一个 table 中不存在的那些 ID2),反之亦然,第一个 table 中的新行(那些在第二 table 中不存在的 ID)。我发现最快的方法是
select SQL_NO_CACHE
tab1.ID
from `tab1`
left join `tab2`
on tab1.ID = tab2.ID2
where
isnull(tab2.ID2)
在约 20 万条记录上耗时 2.5 秒。您可以提出什么建议来获得更快的结果?
使用is null
:
select SQL_NO_CACHE tab1.ID
from `tab1` left join
`tab2`
on tab1.ID = tab2.ID2
where tab2.id2 is null;
此性能应相当于:
select tab1.id
from tab1
where not exists (select 1 from tab2 where tab2.id2 = tab.id);
但这两种方法都值得尝试。
请注意,这些版本与您的要求相反——查找 tab1
中不在 tab2
中的行。如何切换逻辑应该很明显,这取决于你真正想要什么。
SELECT * FROM Tab2 WHERE
NOT EXISTS (SELECT 'x' FROM Tab1 where
Tab1.ID= Tab2.ID)
我想这个查询会给你更快的结果。