Need help in deleting duplicate columns from a table in MySQL?

MySQLMySQLi Database

To delete duplicate columns, use DELETE with INNER JOIN. Following is the syntax −

delete tbl1 from yourTableName anyAliasName1
inner join yourTableName anyAliasName2
where
yourCondition1
and
yourCondition2

Let us create a table −

mysql> create table demo14
−> (
−> id int not null auto_increment primary key,
−> name varchar(30)
−> );
Query OK, 0 rows affected (1.89 sec)

Insert some records into the table with the help of insert command −

mysql> insert into demo14(name) values('John');
Query OK, 1 row affected (0.14 sec)

mysql> insert into demo14(name) values('David');
Query OK, 1 row affected (0.18 sec)

mysql> insert into demo14(name) values('David');
Query OK, 1 row affected (0.09 sec)

mysql> insert into demo14(name) values('Bob');
Query OK, 1 row affected (0.15 sec)

mysql> insert into demo14(name) values('John');
Query OK, 1 row affected (0.45 sec)

mysql> insert into demo14(name) values('Carol');
Query OK, 1 row affected (0.16 sec)

Display records from the table using select statement −

mysql> select *from demo14;

This will produce the following output −

+----+-------+
| id | name  |
+----+-------+
|  1 | John  |
|  2 | David |
|  3 | David |
|  4 | Bob   |
|  5 | John  |
|  6 | Carol |
+----+-------+
6 rows in set (0.00 sec)

Following is the query to delete duplicate columns from the table −

mysql> delete tbl1 from demo14 tbl1
−> inner join demo14 tbl2
−> where
−> tbl1.id < tbl2.id and
−> tbl1.name = tbl2.name
−> ;
Query OK, 2 rows affected (0.20 sec)

Display records from the table using select statement −

mysql> select *from demo14;

This will produce the following output −

+----+-------+
| id | name  |
+----+-------+
|  3 | David |
|  4 | Bob   |
|  5 | John  |
|  6 | Carol |
+----+-------+
4 rows in set (0.00 sec)
raja
Published on 19-Nov-2020 11:19:17
Advertisements