Imanol Barba Sabariego
Imanol Barba Sabariego

Reputation: 115

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

Upvotes: 1

Views: 84

Answers (2)

Zohar Peled
Zohar Peled

Reputation: 82524

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.

Upvotes: 1

Filipe Paulo
Filipe Paulo

Reputation: 134

Use this:

SELECT DISTINCT TABLE_NAME
FROM information_schema.COLUMNS 
WHERE COLUMN_NAME = 'field1' OR COLUMN_NAME = 'field2'

This should return EVERY table name which has a column named 'field1' or 'field2'.

Upvotes: 0

Related Questions