IN 和 NOT IN 是比較常用的關(guān)鍵字,為什么要盡量避免呢?t1表 和 t2表 都是150w條數(shù)據(jù),600M的樣子,都不算大。select * from t1 where phone not in (select phone from t2)
直接就把我跑傻了。。。十幾分鐘,檢查了一下 phone 在兩個(gè)表都建了索引,字段類(lèi)型也是一樣的。原來(lái)not in 是不能命中索引的。。。。改成 NOT EXISTS 之后查詢(xún) 20s ,效率真的差好多。select * from t1
where not EXISTS (select phone from t2 where t1.phone =t2.phone)
2、容易出現(xiàn)問(wèn)題,或查詢(xún)結(jié)果有誤 (不能更嚴(yán)重的缺點(diǎn))以 IN 為例。建兩個(gè)表:test1 和 test2create table test1 (id1 int)
create table test2 (id2 int)
insert into test1 (id1) values (1),(2),(3)
insert into test2 (id2) values (1),(2)
我想要查詢(xún),在test2中存在的 test1中的id 。使用IN的一般寫(xiě)法是:select id1 from test1
where id1 in (select id2 from test2)
select id1 from test1where id1 in (select id1 from test2)
不小心把id2寫(xiě)成id1了 ,會(huì)怎么樣呢?EXCUSE ME!為什么不報(bào)錯(cuò)? 單獨(dú)查詢(xún) select id1 from test2 是一定會(huì)報(bào)錯(cuò): 消息 207,級(jí)別 16,狀態(tài) 1,第 11 行 列名 'id1' 無(wú)效。然而使用了IN的子查詢(xún)就是這么敷衍,直接查出 1 2 3這僅僅是容易出錯(cuò)的情況,自己不寫(xiě)錯(cuò)還沒(méi)啥事兒,下面來(lái)看一下 NOT IN 直接查出錯(cuò)誤結(jié)果的情況:insert into test2 (id2) values (NULL)
我想要查詢(xún),在test2中不存在的 test1中的id 。select id1 from test1
where id1 not in (select id2 from test2)
空白!顯然這個(gè)結(jié)果不是我們想要的。我們想要3。為什么會(huì)這樣呢?原因是:NULL不等于任何非空的值啊!如果id2只有1和2, 那么3<>1 且 3<>2 所以3輸出了,但是 id2包含空值,那么 3也不等于NULL 所以它不會(huì)輸出。(跑題一句:建表的時(shí)候最好不要允許含空值,否則問(wèn)題多多。)
# HOW?
1、用 EXISTS 或 NOT EXISTS 代替
select * from test1
where EXISTS (select * from test2 where id2 = id1 )
select * FROM test1
where NOT EXISTS (select * from test2 where id2 = id1 )
select id1 from test1
INNER JOIN test2 ON id2 = id1
select id1 from test1
LEFT JOIN test2 ON id2 = id1
where id2 IS NULL
PS:那我們死活都不能用 IN 和 NOT IN 了么?并沒(méi)有,一位大神曾經(jīng)說(shuō)過(guò),如果是確定且有限的集合時(shí),可以使用。如 IN (0,1,2)。作者:Hydor
來(lái)源:http://cnblogs.com/hydor/p/5391556.html
該文章在 2025/6/26 22:08:46 編輯過(guò)