2012-05-22 47 views

回答

5
DELETE FROM table1 
WHERE id NOT IN (13, 19, 22, 3129) 

在PHP中,您可以使用implode()函數來構建IN子句。

$items = implode(",", $items);  
$sql = "DELETE FROM table1 WHERE id NOT IN ({$items})"; 
1

使用破滅,但不要設置相同的數組變量,你可能在你的程序以後將其用作也是不推薦或作爲良好的編程習慣改變,就像一個變量的數據類型。

$items= array(13, 19, 22, 3129); 
$sql = sprintf("delete from tbl where id_col not in (%s)",implode(",", $items)); 
1

如果mytable是大,但保持條目的數量小,這裏有一個更快的方式

$items= array(13, 19, 22, 3129); 
$sql = "CREATE TABLE mynewtable LIKE mytable"; 
mysql_query($sql); 
$id_list = sprintf("(%s)",implode(",", $items)); 
$sql = "INSERT INTO mynewtable SELECT * FROM mytable WHERE id_col IN " . $id_list; 
mysql_query($sql); 
$sql = "DROP TABLE mytable"; 
mysql_query($sql); 
$sql = "ALTER TABLE mynewtable RENAME mytable"; 
mysql_query($sql);