1

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

aynber
  • 22,380
  • 8
  • 50
  • 63

2 Answers2

1

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.

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
0

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'.

Filipe Paulo
  • 134
  • 6