[英]Is NOT IN faster than inequals in MySQL?
我試圖找出是否有一種更有效的方法來為MySQL 5.5編寫存儲過程。 本質上,存儲過程將截斷我創建的所有表中的數據,除了少數幾個。 我嘗試通過執行以下操作來實現這一目標……
create procedure truncate_tables()
begin
declare tab_name varchar(64);
declare done tinyint unsigned default 0;
declare table_cur cursor for select t.table_name
from
information_schema.schemata s
inner join information_schema.tables t on s.schema_name = t.table_schema
where
s.schema_name = database()
and t.table_type = 'BASE TABLE'
and t.table_name not like 'DATABASE%'
and t.table_name != ‘my_table_1’
and t.table_name != ‘my_table_2’
and t.table_name != ‘my_table_3’
…
and t.table_name != ‘my_table_n-1’
and t.table_name != ‘my_table_n’;
declare continue handler for not found set done = 1;
open table_cur;
repeat
fetch table_cur into tab_name;
set @cmd = concat('truncate table ', tab_name);
prepare stmt from @cmd;
execute stmt;
until done end repeat;
close table_cur;
end
當我探索更快的方法時,是否應該將我的眾多不等式子句替換為“ NOT IN(list)”子句? 不確定哪種方法在MySQL中執行速度更快,或者是否還有其他效率需要提高。
NOT IN
是一種更清晰的代碼編寫方式,它使代碼更具可維護性(更易於添加新表名,更易於理解)。
您正在處理的系統表可能不那么大。 您正在執行的聯接可能比where
子句的開銷更大。 並且,您正在使用游標訪問數據。 對於where
子句的某些微優化,性能差異可能可以忽略不計。
not in
。
並且,如果您真的很擔心,請測試這兩種方法並選擇速度更快的一種。
要在您的問題的標題中回答該問題,不,就生成的執行計划而言,性能沒有差異。 這兩種形式是等效的。 (在實際解析該語句時,性能可能會略有不同,但這將無法測量。
我希望大部分時間都在實際執行單個TRUNCATE語句中。
你不需要加入到schemata
的表,你可以參考table_schema
列tables
中的謂語表:
SELECT t.table_name
FROM information_schema.tables t
WHERE t.table_schema = DATABASE()
AND t.table_type = 'BASE TABLE'
AND ...
謂詞
foo NOT IN ('a','b','c')
相當於
(foo != 'a' AND foo != 'b' AND foo != 'c')
執行計划沒有什么區別; 在這種情況下, NOT IN
只是避免我們不得不重復對foo
的引用,並使該語句更易於閱讀,理解和維護。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.