Home >Database >Mysql Tutorial >How to Efficiently Delete Data Across Multiple MySQL Tables with a Single Query?
When working with multiple tables related by a common field, it may be necessary to delete information about a user from all tables simultaneously. Rather than executing multiple DELETE statements, this query explores the possibility of performing the deletion in a single query.
The proposed query involves using multiple DELETE statements separated by semicolons:
DELETE FROM table1 WHERE user_id='$user_id'; DELETE FROM table2 WHERE user_id='$user_id'; DELETE FROM table3 WHERE user_id='$user_id'; DELETE FROM table4 WHERE user_id='$user_id';
However, according to the MySQL documentation, this is not the optimal approach. The documentation suggests utilizing the following syntax:
DELETE t1, t2 FROM t1 INNER JOIN t2 INNER JOIN t3 WHERE t1.id=t2.id AND t2.id=t3.id;
This query allows for the deletion of rows from multiple tables based on a specified condition in the WHERE clause. In this case, the condition would be t1.user_id='$user_id'.
Utilizing this approach simplifies the deletion process and ensures that the data from all relevant tables is removed simultaneously.
The above is the detailed content of How to Efficiently Delete Data Across Multiple MySQL Tables with a Single Query?. For more information, please follow other related articles on the PHP Chinese website!