选择MySQL中不包含某个列的表

时间:2011-03-10 20:44:17

标签: mysql sql select information-schema

我正在尝试选择所有没有名为“unique”的列的表。我可以选择使用它的所有表:

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

是否有一种简单的方法来修改SELECT语句,以便列出所有没有该列的表?这看起来很简单,但我无法弄明白,也无法在论坛上找到答案。

由于

4 个答案:

答案 0 :(得分:6)

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'

答案 1 :(得分:1)

如果服务器中只存在一个数据库,则上述查询有效。如果没有,还将列出其他数据库中的表。考虑这个从特定数据库中选择表的简化版本。总而言之,这是一个很棒的亮点!

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');

答案 2 :(得分:0)

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

答案 3 :(得分:0)

简单的反转:

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');