这是正确的做法。(只是对表名周围的“[]”大括号感到困惑——这些很可能不是实际名称的一部分,因此需要删除)
此外,这是一种有效的方法:由于您为两者table_schema
以及 for提供了一个常量table_name
,因此您正在使用INFORMATION_SCHEMA 优化,因为该表甚至没有打开:
explain select count(*) from information_schema.tables where table_schema='world' and table_name='City';
+----+-------------+--------+------+---------------+-------------------------+---------+------+------+---------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+--------+------+---------------+-------------------------+---------+------+------+---------------------------------------------------+
| 1 | SIMPLE | tables | ALL | NULL | TABLE_SCHEMA,TABLE_NAME | NULL | NULL | NULL | Using where; Skip_open_table; Scanned 0 databases |
+----+-------------+--------+------+---------------+-------------------------+---------+------+------+---------------------------------------------------+
提供的“SHOW TABLES”解决方案也很好——就 Java/Python/Whatever 代码而言几乎相同。结果是一个有效的 ResultSet:
SHOW TABLES FROM world LIKE 'City';
+------------------------+
| Tables_in_world (City) |
+------------------------+
| City |
+------------------------+
但是为了完成这个故事:它不是标准的 SQL 语法——所以如果你使用某种框架,比如某种 ORM,你可能并不总是能够处理这种类型的查询(我记得 EJB3 会不让你这样做)。
此外,在服务器端解析非常困难,请参阅:Reading results of SHOW statements, on server side,尽管这可能不是您关心的问题。