Search code examples
mysqlsqldatabase-schema

SQL list all tables with certain column names


I'd like to make a SQL query to a MySQL 5.6 server to return me all the tables that contains AT LEAST the following column names:

field1 
field2

I've seen examples here but they only cover having exactly one column name or one between many possible.

For example, if I have these 4 tables:

TABLE1
field1 field2 field3

TABLE2
field2 field4

TABLE3
field1 field3

TABLE4
field1 field2

Since I'm querying the tables that have AT LEAST "field1" AND "field2", the result should be:

TABLE1
TABLE4

I tried doing a self join with the INFORMATION_SCHEMA.COLUMNS table but I can't get it right...

Thanks for your help


Solution

  • Try this:

    SELECT DISTINCT T1.TABLE_NAME
    FROM INFORMATION_SCHEMA.COLUMNS T1
    INNER JOIN INFORMATION_SCHEMA.COLUMNS T2 ON(T1.TABLE_NAME = T2.TABLE_NAME)
    WHERE T1.COLUMN_NAME = 'field1'
    AND T2.COLUMN_NAME = 'field2'
    

    Note: code was written directly here, not tested.