在我的数据库中,我有 32 个表,并且大多数表都包含相同的 id。如何删除整个数据库中在一个查询中仅包含特定 ID 的所有数据(我的意思是包含该特定 ID 的每个表)。
DELETE * from (ALL TABLES) where id = 3;
最佳答案
好问题。查询可能是最佳解决方案。
我在下面给出了使用 PHP 作为您指定的 PHP 标签的解决方案
<?php
require("db_connect.php");
$tables = mysqli_query($con, "SHOW TABLES FROM dbname");
while ($row = mysqli_fetch_assoc($tables)) {
$table_name = $row["Tables_in_dbname"];
mysqli_query($con, "DELETE FROM $table_name WHERE `id`=3");
}
?>
或
再创建一个表,您可以在其中每日记录需要从所有表中删除的 id
条目,并且每天您可能会得到不同的 id
列表以从所有表中删除.
在下面我创建了一个表ids_to_delete
,其中我指定了要删除的 id 列表。
<?php
require("db_connect.php");
//get ids from table where specified ids to be deleted
$ids = mysqli_query($con, "SELECT `id` FROM `ids_to_delete`");
$id_list = '';
//create ids list like 1,4,3,9,5,6,...
while ($row_id = mysqli_fetch_assoc($tables)) {
$id_list .= $row_id['id'] . ',';
}
$id_list = trim($id_list, ',');
$tables = mysqli_query($con, "SHOW TABLES FROM dbname");
while ($row = mysqli_fetch_assoc($tables)) {
$table_name = $row["Tables_in_dbname"];
mysqli_query($con, "DELETE FROM $table_name WHERE `id` IN ($id_list)");
}
//clear the ids_to_delete table
mysqli_query($con,"DELETE FROM `ids_to_delete`");
?>
关于PHP/MySQL : How to delete all data from database which contains specific id in one query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39674105/