2013-05-22 60 views
0

我需要能夠檢測數據庫和/或表是否存在於單個查詢中,從而採取相應的行動。我有這樣的fugly查詢工作:檢測數據庫和表是否存在於同一個查詢中

SELECT * FROM 

(SELECT COUNT(*) AS `database` 
FROM INFORMATION_SCHEMA.SCHEMATA 
WHERE SCHEMATA.SCHEMA_NAME="database_name") AS foo, 

(SELECT COUNT(*) AS `table` 
FROM INFORMATION_SCHEMA.TABLES 
WHERE table_schema = "database_name" 
AND table_name = "table_name") AS bar 

該查詢返回:

database table 
1   0 

但是......也許有一個更好的方法在那裏。

+0

使用'UNION ALL'? – Kermit

+0

AFAIK表和數據庫是保留關鍵字,不應使用。 –

+0

我不確定。表格有不同的結構。 – Veehmot

回答

1

使用LEFT JOIN:

SELECT schemata.schema_name AS `database_name`, tables.table_name 
FROM INFORMATION_SCHEMA.SCHEMATA schemata 
LEFT JOIN INFORMATION_SCHEMA.TABLES tables 
    ON schemata.schema_name = tables.table_schema 
    AND tables.table_name = "table_name" 
WHERE SCHEMATA.SCHEMA_NAME="database_name" 
0

這也將工作,雖然我不知道它的任何漂亮:)

SELECT 
    MAX(CASE 
     WHEN table_schema = 'database_name' THEN 1 
     ELSE 0 
     END) AS `database` 
, MAX(CASE 
     WHEN table_schema = 'database_name' AND table_name = 'table' THEN 1 
     ELSE 0 
     END) AS `table` 
FROM information_schema.tables; 
相關問題