MySQL选择具有多个特定列的所有表
作者:互联网
我想获取具有3个特定列的所有表名.
我想要的是从信息模式中获取所有包含columnA AND columnB AND columnC的表名.
目前,我正在使用类似的查询
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME='columnA'
AND TABLE_SCHEMA='mysampledatabase';
如何扩展上述查询并选择包含列名称columnA和columnB的表?
我遇到了this answer和其他类似的答案.他们回答了以下问题:
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('columnA','ColumnB')
AND TABLE_SCHEMA='YourDatabase';
但是,他们选择具有3列之一的任何表.我认为这是因为WHERE COLUMN_NAME IN(‘columnA’,’ColumnB’,’ColumnC’)相当于COLUMN_NAME =’columnA’或COLUMN_NAME =’columnB’或COLUMN_NAME =’columnC’
我尝试将WHERE子句替换为WHERE COLUMN_NAME =’columnA’AND COLUMN_NAME =’columnB’AND COLUMN_NAME =’columnC’,这显然不会返回任何结果,因为COLUMN_NAME一次只能为1值!
解决方法:
这是可能对您有帮助的查询:
SELECT`TABLE_SCHEMA`, `table_name`,c1.`column_name`,c2.`column_name`,c3.`column_name` FROM `COLUMNS` C1
INNER JOIN `COLUMNS` C2 USING(`TABLE_SCHEMA`, `TABLE_NAME`)
INNER JOIN `COLUMNS` C3 USING(`TABLE_SCHEMA`, `TABLE_NAME`)
WHERE c1.`column_name` = 'col1'
AND c2.`column_name` = 'col2'
AND c3.`column_name` = 'col3';
但是,您需要为每个要查找的列添加或删除多余的JOIN.
现在,我认为这有点繁重且难以理解,这是另一种选择:
SELECT table_schema, table_name, count(*) AS `TablesCount` FROM `COLUMNS`
WHERE `column_name` IN ('col1','col1','col1')
GROUP BY table_schema, table_name
HAVING `TablesCount` = 3
TablesCount应该等于您要查找的列数.如果是这样,则您的表具有所有必需的列
标签:information-schema,mysql 来源: https://codeday.me/bug/20191029/1960747.html