Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql - delete from multiple tables with one query [duplicate]

Tags:

mysql

I have 4 tables that stores different information about a user in each. Each table has a field with user_id to identify which row belongs to which user. If I want to delete the user is this the best way to delete that users information from multiple tables? My objective is to do it in one query.

Query:

"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';"; 
like image 699
Jason Avatar asked Jan 29 '11 22:01

Jason


People also ask

How do I delete multiple table records in one query?

Your eventID in all table will make it work. For deleting records from multiple tables: You could define Foreign Key constraints (which you have defined as EventID) for the other tables that reference the master table's ID with ON DELETE CASCADE. This would cause the related rows in those tables to be deleted.

Can you delete from two tables at once?

The syntax also supports deleting rows from multiple tables at once. To delete rows from both tables where there are matching id values, name them both after the DELETE keyword: DELETE t1, t2 FROM t1 INNER JOIN t2 ON t1.id = t2.id; What if you want to delete nonmatching rows?

How do you delete data from 3 tables in SQL?

If it works if all tables have records, try using LEFT JOIN instread of INNER JOIN. Also, You had some mess with Your joins ON conditions. Try it like this: delete relativedata, crawls, stored from relativedata LEFT join crawls on relativedata.

How do I delete multiple tables in MySQL?

From the manual: You can specify multiple tables in a DELETE statement to delete rows from one or more tables depending on the particular condition in the WHERE clause. However, you cannot use ORDER BY or LIMIT in a multiple-table DELETE. The table_references clause lists the tables involved in the join.


1 Answers

Apparently, it is possible. From the manual:

You can specify multiple tables in a DELETE statement to delete rows from one or more tables depending on the particular condition in the WHERE clause. However, you cannot use ORDER BY or LIMIT in a multiple-table DELETE. The table_references clause lists the tables involved in the join. Its syntax is described in Section 12.2.8.1, “JOIN Syntax”.

The example in the manual is:

DELETE t1, t2 FROM t1 INNER JOIN t2 INNER JOIN t3 WHERE t1.id=t2.id AND t2.id=t3.id; 

should be applicable 1:1.

like image 65
Pekka Avatar answered Sep 26 '22 21:09

Pekka