我有一个查询
SELECT DISTINCT phoneNum
FROM `Transaction_Register`
WHERE phoneNum NOT IN (SELECT phoneNum FROM `Subscription`)
LIMIT 0 , 1000000
执行 b/c 表需要太多时间,Transaction_Register
有数百万条记录是否有上述查询的替代方法,如果有的话,我将不胜感激。
另一种方法是使用 LEFT JOIN:
select distinct t.phoneNum
from Transaction_Register t
left join Subscription s
on t.phoneNum = s.phoneNum
where s.phoneNum is null
LIMIT 0 , 1000000;
我怀疑是否LEFT JOIN
真的表现得比NOT IN
. 我只是用下面的表结构进行了一些测试(如果我错了请纠正我):
account (id, ....) [42,884 rows, index by id]
play (account_id, playdate, ...) [61,737 rows, index by account_id]
(1) 查询LEFT JOIN
SELECT * FROM
account LEFT JOIN play ON account.id = play.account_id
WHERE play.account_id IS NULL
(2) 查询NOT IN
SELECT * FROM
account WHERE
account.id NOT IN (SELECT play.account_id FROM play)
使用 LIMIT 0 进行速度测试,...
LIMIT 0,-> 100 150 200 250
-------------------------------------------------------------------------
LEFT 3.213s 4.477s 5.881s 7.472s
NOT EXIST 2.200s 3.261s 4.320s 5.647s
--------------------------------------------------------------------------
Difference 1.013s 1.216s 1.560s 1.825s
随着我增加限制,差异越来越大
EXPLAIN
(1) 查询LEFT JOIN
SELECT_TYPE TABLE TYPE ROWS EXTRA
-------------------------------------------------
SIMPLE account ALL 42,884
SIMPLE play ALL 61,737 Using where; not exists
(2) 查询NOT IN
SELECT_TYPE TABLE TYPE ROWS EXTRA
-------------------------------------------------
SIMPLE account ALL 42,884 Using where
DEPENDENT SUBQUERY play INDEX 61,737 Using where; Using index
似乎 LEFT JOIN 没有使用索引
(1) 查询LEFT JOIN
帐户和游戏之间的 LEFT JOIN 后将产生 42,884 * 61,737 = 2,647,529,508 行。然后检查这些行上的 play.account_id 是否为 NULL。
(2) 查询NOT IN
二进制搜索以 log2(N) 为项目存在。这意味着 42,884 * log2(61,737) = 686,144 步