2012-12-03 164 views
0

我試圖從指定數據庫中選擇包含列'lang'和'project'的所有表。這是我在做什麼:MySQL查詢按列名選擇表名

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」列的表,但沒有「項目」列。而且老實說,我想不出哪裏開始...

感謝您的幫助

回答

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) 
+0

謝謝你,我的朋友。只要此操作可用,我會盡快接受此答案。順便說一句:在第二個查詢中,ISC1應更改爲ISC – Marius

+0

您是對的,已更正。 –