简体   繁体   English

删除但将具有ID的行保留在数组php / mysql中

[英]Delete but keep rows with id in array php/mysql

So I have a $items= array(13, 19, 22, 3129); 所以我有一个$items= array(13, 19, 22, 3129);

How can I simply not include the rows with these id's in my DELETE query sql? 如何在我的DELETE查询sql中简单地不包含具有这些ID的行?

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

In PHP, you can use the implode() function to build the IN clause. 在PHP中,可以使用implode()函数构建IN子句。

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

Use implode but dont set the same array variable as you might be use it later in your program as also it is not recommended or taken as good programming practice to change the data type of a variable just like that. 使用implode,但不要设置与稍后在程序中使用的数组变量相同的数组变量,因为也不建议或将其作为良好的编程习惯来更改变量的数据类型。

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

If mytable is big but the number of entries to keep is small, here is a faster way 如果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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM