Monday 24 July 2017

How to delete records from multiple tables in MYSQL with one query

Delete records from multiple tables with one query.

CREATE TABLE table_a (
  id INT(11) DEFAULT NULL
);

CREATE TABLE table_b (
  id INT(11) DEFAULT NULL
);

INSERT INTO table_a VALUES 
  (2),
  (3),
  (1);

INSERT INTO table_b VALUES 
  (2),
  (5),
  (1);

 

Delete records:

DELETE t1, t2
FROM
  table_a t1
JOIN table_b t2
  ON t1.id = t2.id
WHERE
  t1.id = 1;

 

Check results:

SELECT * FROM table_a;
+------+
| id   |
+------+
|    2 |
|    3 |
+------+

SELECT * FROM table_b;
+------+
| id   |
+------+
|    2 |
|    5 |
+------+

1 comment:

Advertisement

Advertisement