// Select 1 from table_name will return false if the table does not exist.
$val = mysql_query('select 1 from `table_name` LIMIT 1');
if($val !== FALSE)
{
//DO SOMETHING! IT EXISTS!
}
else
{
//I can't find it...
}
诚然,它比 PHP 习惯更Pythonic,但另一方面,您不必担心处理大量额外数据。
Edit
因此,截至我撰写此消息时,该答案已至少被标记两次。假设我犯了一些巨大的错误,我就跑了一些基准 http://pastebin.com/7SbjVEYx,这就是我发现当表不存在时我的解决方案比最接近的替代方案快 10% 以上,而当表存在时我的解决方案快 25% 以上:
:::::::::::::::::::::::::BEGINNING NON-EXISTING TABLE::::::::::::::::::::::::::::::
23.35501408577 for bad select
25.408507823944 for select from schema num rows -- calls mysql_num_rows on select... from information_schema.
25.336688995361 for select from schema fetch row -- calls mysql_fetch_row on select... from information_schema result
50.669058799744 for SHOW TABLES FROM test
:::::::::::::::::::::::::BEGINNING EXISTING TABLE::::::::::::::::::::::::::::::
15.293519973755 for good select
20.784908056259 for select from schema num rows
21.038464069366 for select from schema fetch row
50.400309085846 for SHOW TABLES FROM test
我尝试针对 DESC 运行此命令,但在 276 秒后超时(我的答案为 24 秒,276 秒未能完成对不存在表的描述)。
为了更好地衡量,我正在对一个只有四个表的模式进行基准测试,这是一个几乎全新的 MySQL 安装(这是迄今为止唯一的数据库)。要查看导出,请查看here http://pastebin.com/icWFpf0b.
而且更进一步
这个特定的解决方案也更加独立于数据库,因为相同的查询可以在 PgSQL 和 Oracle 中工作。
FINALLY
mysql_query()
对于不是“此表不存在”的错误,返回 FALSE。
如果你需要保证表doesn't存在、使用mysql_errno()
获取错误代码并将其与相关的进行比较MySQL 错误 https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html.