0

I need to be able to detect if the database and/or the table exists on a single query, to act accordingly. I have this fugly query working:

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

This query returns:

database    table
1           0

But... Maybe there is a better method out there.

4

2 回答 2

1

使用左连接:

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"
于 2013-05-22T14:41:44.957 回答
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;
于 2013-05-22T14:45:48.280 回答