How to find all tables that contains two specific columns in MySQL?


To find two specific column names, use information_schema.columns Here, I am using Id in place of columnA and Name in place of columnB −

mysql> select table_name as TableNameFromWebDatabase
   -> from information_schema.columns
   -> where column_name IN ('Id', 'Name')
   -> group by table_name
   -> having count(*) = 3;

This will produce the following output. Following are the tables with columns Id and Name −

+--------------------------+
| TableNameFromWebDatabase |
+--------------------------+
| student                  |
| distinctdemo             |
| secondtable              |
| groupconcatenatedemo     |
| indemo                   |
| ifnulldemo               |
| demotable211             |
| demotable212             |
| demotable223             |
| demotable233             |
| demotable251             |
| demotable255             |
+--------------------------+
12 rows in set (0.25 sec)

To prove, let us check the description of one of the tables. Following is the query −

mysql> desc demotable233;

This will produce the following output. Here, you can see we have the Int and Name columns −

+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
|    Id | int(11)     | NO   | PRI | NULL    | auto_increment |
| Name  | varchar(20) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
raja
Published on 08-Nov-2019 10:43:35
Advertisements