且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查PHP表是否存在MySQL表?

更新时间:2021-11-03 10:34:58

// 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...
}

不可否认,它更像Pythonic,而不是PHP习惯用语,但另一方面,你不必担心处理大量的额外数据。

Admittedly, it is more Pythonic than of the PHP idiom, but on the other hand, you don't have to worry about dealing with a copious amount of extra data.

所以,这个答案至少在我撰写此邮件时被标记为两次。假设我犯了一些巨大的错误,我去了,我跑了一些基准,这就是我发现我的当表不存在时,解决方案比最近的替代方案快10%以上,当表存在时,解决方案的速度提高了25%以上:

So, this answer has been marked down at least twice as of the time I am writing this message. Assuming that I had made some gargantuan error, I went and I ran some benchmarks, and this is what I found that my solution is over 10% faster than the nearest alternative when the table does not exist, and it over 25% faster when the table does exist:

:::::::::::::::::::::::::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未能完成对现有表的描述)。

I tried running this against DESC, but I had a timeout after 276 seconds (24 seconds for my answer, 276 to fail to complete the description of a non existing table).

为了更好的衡量,我正在针对只有四个表的模式进行基准测试,这是一个几乎全新的MySQL安装(这是迄今为止唯一的数据库)。要查看导出,请查看此处

For good measure, I am benchmarking against a schema with only four tables in it and this is an almost fresh MySQL install (this is the only database so far). To see the export, look here.

这个特定的解决方案也更加独立于数据库,因为相同的查询将在PgSQL和Oracle中运行。

This particular solution is also more database independent as the same query will work in PgSQL and Oracle.

对于不是此表不存在的错误,mysql_query()返回FALSE。

如果您需要保证表不存在,请使用 mysql_errno()获取错误代码并将其与相关的 MySQL错误进行比较

If you need to guarantee that the table doesn't exist, use mysql_errno() to get the error code and compare it to the relevant MySQL errors.