Monday, April 12, 2010

MySQL

Deleting rows from multiple tables in MySQL:

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.

The syntax:
DELETE FROM t1, t2 USING t1 INNER JOIN t2 INNER JOIN t3
WHERE t1.id=t2.id AND t2.id=t3.id;

Example:

Let's consider two tables:


firstName
idFIRST NAME
1Peter
2James
3Rita
4Joanna
9Ron

lastName
idLAST NAME
1Henderson
2Morrison
3Potter
4Mullick
5Wayne

I can delete the rows with ID-1,2,3 and 4 in table-1(firstName) and table-2(lastName) with the following query:
DELETE FROM firstName, lastName USING firstName INNER JOIN lastName
WHERE firstName.id=lastName.id

Voila!

No comments:

Post a Comment