为了使用 MySQL 检查数据库中是否已存在表,您可以使用 INFORMATION_SCHEMA.TABLES。以下是语法 -
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ‘yourDatabaseName’ AND TABLE_NAME = ’yourTableName’;
让我们实现上述语法以检查数据库中是否已存在表。
情况 1:当表存在时 -
mysql> SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'sample' AND TABLE_NAME = 'DemoTable';
这将产生以下输出 -
+--------------+ | TABLE_NAME | +--------------+ | DemoTable | +--------------+ 1 row in set (0.01 sec)
情况 2:当表不存在时 -
mysql> SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA= 'sample' AND TABLE_NAME= 'DemoTable2';
这将产生以下输出 -
Empty set (0.01 sec)