我需要能够检测单个查询中是否存在数据库和/或表,以便相应地执行操作。我有这个讨厌的查询工作:
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 :(得分: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"
答案 1 :(得分: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;