简体   繁体   中英

Select tables that do not contain a certain column in MySQL

I am trying to select all tables that do not have column named 'unique'. I can select all tables that have it using:

SELECT DISTINCT TABLE_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'unique'
AND TABLE_SCHEMA ='database';

Is there a simple way to modify the SELECT statement so it lists all tables that do not have that column? This seems like it would be simple, but I can't figure it out, and can't find an answer on the forum.

Thanks

select
t.*
from INFORMATION_SCHEMA.TABLES as t
    left join INFORMATION_SCHEMA.COLUMNS as c
    on c.TABLE_NAME = t.TABLE_NAME
    and c.TABLE_SCHEMA = t.TABLE_SCHEMA
    and c.COLUMN_NAME = 'unique'
where c.COLUMN_NAME is null
and t.TABLE_SCHEMA = 'database'

The above queries work, if only one database exists in the server. If not, tables from other databases will also be listed. Consider this simplified version that picks tables from a particular DB. All in all, this is a great highlight!

SELECT DISTINCT TABLE_NAME 
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_SCHEMA = 'DATABASE_NAME' 
AND TABLE_NAME NOT IN (SELECT DISTINCT TABLE_NAME 
                            FROM INFORMATION_SCHEMA.COLUMNS 
                           WHERE COLUMN_NAME = 'FIELD_NAME' 
                             AND TABLE_SCHEMA ='DATABASE_NAME');
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME NOT IN (
SELECT DISTINCT TABLE_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'unique'
AND TABLE_SCHEMA ='database')

A simple inversion:

SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME NOT IN

(SELECT DISTINCT TABLE_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'unique'
AND TABLE_SCHEMA ='database');

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