我正在使用MySQL。表引擎是MyIsam
哪种方法更快?
DELETE FROM TABLE WHERE id IN (1,2,3);
或
DELETE FROM TABLE WHERE id = 1;
DELETE FROM TABLE WHERE id = 2;
DELETE FROM TABLE WHERE id = 3;
id字段是PRIMARY KEY
哪一个会更快?
答案 0 :(得分:5)
IN应该更快,因为mysql将在第二个解决方案中的每个查询后更新索引并移动数据块,而第一个查询只会发生一次。
这里有一些关于MySQL的测试(对于一个有一个int列和3个varchars的表,填充了随机数据和WHERE中的列上的索引...没有索引没有意义,因为它需要更多在这两种情况下的时间......但是仍然有3个查询的速度比IN慢。
mysql> call prepare_data();
Query OK, 1 row affected (34.25 sec)
mysql> delete from t1 where trt in (5, 6, 7);
Query OK, 300049 rows affected (5.25 sec)
mysql> call prepare_data();
Query OK, 1 row affected (35.18 sec)
mysql> delete from t1 where trt=5;delete from t1 where trt=6;delete from t1 where trt=7;
Query OK, 99961 rows affected (2.25 sec)
Query OK, 99842 rows affected (2.38 sec)
Query OK, 99558 rows affected (2.69 sec)
mysql>
所以,这三个查询花了很多时间7.39s vs 5.25s IN,增加了40%)。这是prepare_data程序:
DELIMITER $$
CREATE PROCEDURE prepare_data()
BEGIN
DECLARE i INT DEFAULT 0;
TRUNCATE TABLE t1;
WHILE i < 1000000 DO
INSERT INTO t1 (a, b, c, trt) VALUES ('fasdfadsf', 'asdfasdfa', 'asdfasdf', FLOOR( 1 + RAND( ) *10 ));
SET i = i + 1;
END WHILE;
END $$
DELIMITER ;
答案 1 :(得分:2)
SQL Server 2008 R2 Express,IBM t60p笔记本电脑,Core Duo T2500 2.0GHz CPU,7200rpm HDD
100000行(col2上没有索引,col1带id,col2带有0到10之间的随机数)
测试1:三次查询
TEST 2:单一查询
用于插入的查询:
truncate table testTable
DECLARE @counter int, @col2 int
SELECT @counter=0, @col2=RAND(@@spid + cpu + physical_io)
FROM master..sysprocesses where spid=@@spid
WHILE (@counter < 1000000)
BEGIN
SELECT @counter=@counter + 10,
@col2= CONVERT(int, RAND() * 100) % 10
INSERT testTable VALUES (@counter, @col2)
END
用于衡量的查询:
DECLARE @StartTime datetime,@EndTime datetime
SELECT @StartTime=GETDATE()
DELETE FROM testTable WHERE col2 = 7;
DELETE FROM testTable WHERE col2 = 8;
DELETE FROM testTable WHERE col2 = 9;
--DELETE FROM testTable where col2 in (7,8,9);
SELECT @EndTime=GETDATE()
SELECT DATEDIFF(ms,@StartTime,@EndTime) AS [Duration in microseconds]