MySQL查询按列名选择表名

时间:2012-12-03 15:46:22

标签: mysql information-schema

我正在尝试从指定数据库中选择包含列'lang'和'project'的所有表。这就是我正在做的事情:

SELECT DISTINCT(ISC1.TABLE_NAME) AS `table` FROM INFORMATION_SCHEMA.COLUMNS AS ISC1 
JOIN INFORMATION_SCHEMA.COLUMNS AS ISC2 ON 
    (ISC1.TABLE_SCHEMA=ISC2.TABLE_SCHEMA AND ISC1.TABLE_NAME=ISC2.TABLE_NAME AND ISC2.COLUMN_NAME='project') 
WHERE ISC1.COLUMN_NAME='lang' AND ISC2.COLUMN_NAME='project' AND ISC1.TABLE_SCHEMA='some_database'
  • 它确实有效,但我觉得写这种查询是一种不好的方式。如果有人可以改进,那就太好了。
  • 现在我必须更改此查询以选择所有具有'lang'列但没有'project'列的表。老实说,我无法弄清楚从哪里开始......

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

SELECT DISTINCT(ISC1.TABLE_NAME) AS `table`
FROM INFORMATION_SCHEMA.COLUMNS AS ISC1,
    INFORMATION_SCHEMA.COLUMNS AS ISC2 
WHERE ISC1.TABLE_SCHEMA=ISC2.TABLE_SCHEMA
AND ISC1.TABLE_NAME=ISC2.TABLE_NAME
AND ISC2.COLUMN_NAME='project'
AND ISC1.COLUMN_NAME='lang'
AND ISC1.TABLE_SCHEMA='some_database'

没有项目栏:

SELECT DISTINCT(ISC.TABLE_NAME) AS `table`
FROM INFORMATION_SCHEMA.COLUMNS AS ISC
WHERE ISC.COLUMN_NAME='lang'
AND ISC.TABLE_SCHEMA='some_database'
AND NOT EXISTS(SELECT *
    FROM INFORMATION_SCHEMA.COLUMNS C
    WHERE C.COLUMN_NAME = 'project'
    AND C.TABLE_NAME=ISC.TABLE_NAME
    AND C.TABLE_SCHEMA=ISC.TABLE_SCHEMA)