Perform Multi-table delete in MySQL


For this, you can use DELETE command. Let us first create a table −

mysql> create table DemoTable1
(
   Id int,
   Name varchar(20)
);
Query OK, 0 rows affected (0.63 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(1,'Chris');
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable1 values(2,'David');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1 values(3,'Bob');
Query OK, 1 row affected (0.20 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

+------+-------+
| Id   | Name  |
+------+-------+
|    1 | Chris |
|    2 | David |
|    3 | Bob   |
+------+-------+
3 rows in set (0.00 sec)

Here is the query to create second table −

mysql> create table DemoTable2
(
   ClientId int,
   ClientName varchar(20)
);
Query OK, 0 rows affected (1.19 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2 values(101,'Mike');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable2 values(110,'Bob');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable2 values(120,'Adam');
Query OK, 1 row affected (0.60 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2;

This will produce the following output −

+----------+------------+
| ClientId | ClientName |
+----------+------------+
|      101 | Mike       |
|      110 | Bob        |
|      120 | Adam       |
+----------+------------+
3 rows in set (0.00 sec)

Here is the query for multi-table delete −

mysql> delete from DemoTable1 where Name='Bob';
Query OK, 1 row affected (0.23 sec)
mysql> delete from DemoTable2 where ClientName='Bob';
Query OK, 1 row affected (0.27 sec)

Let us check the first table records −

mysql> select *from DemoTable1;

This will produce the following output −

+------+-------+
| Id   | Name  |
+------+-------+
| 1    | Chris |
| 2    | David |
+------+-------+
2 rows in set (0.00 sec)

Let us check the second table records −

mysql> select *from DemoTable2;

This will produce the following output −

+----------+------------+
| ClientId | ClientName |
+----------+------------+
|      101 | Mike       |
|      120 | Adam       |
+----------+------------+
2 rows in set (0.00 sec)
raja
Published on 10-Oct-2019 15:02:07
Advertisements