简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM