我希望获得具有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' OR COLUMN_NAME = 'columnB' OR COLUMN_NAME = 'columnC'
我试图用WHERE COLUMN_NAME='columnA' AND COLUMN_NAME='columnB' AND COLUMN_NAME='columnC'
替换WHERE子句,这显然不会返回任何结果,因为COLUMN_NAME
一次只能是1个值!
答案 0 :(得分:2)
以下是可能对您有所帮助的查询:
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应该与您要查找的列数相等。如果是这样,则表格中包含所有必需的列
答案 1 :(得分:2)
这是一个更快的版本:
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('columnA','columnB','columnC')
group by TABLE_NAME
having count(distinct COLUMN_NAME) = 3
在上面有计数的查询将没有。 IN
短语中指定的列数。
或尝试跟随(但它会为很多列造成灾难。所以要避免它)
SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME IN
( SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'columnA' )
and TABLE_NAME in
( SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'columnB')
and TABLE_NAME in
( SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'columnC')