有没有一种方法来检查表是否存在,而不选择和检查它的值?

也就是说,我知道我可以去SELECT testcol FROM testtable并检查返回字段的计数,但似乎必须有一个更直接/优雅的方式来做到这一点。


当前回答

我在php中使用这个。

private static function ifTableExists(string $database, string $table): bool
    {
        $query = DB::select("
            SELECT 
                IF( EXISTS 
                    (SELECT * FROM information_schema.COLUMNS
                        WHERE TABLE_SCHEMA = '$database'
                        AND TABLE_NAME = '$table'
                        LIMIT 1),
                1, 0)
                AS if_exists
        ");

        return $query[0]->if_exists == 1;
    }

其他回答

您可以查询INFORMATION_SCHEMA表的系统视图:

SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'databasename'
AND table_name = 'testtable';

如果没有返回行,则表不存在。

下面是一个不是SELECT * FROM的表

SHOW TABLES FROM `db` LIKE 'tablename'; //zero rows = not exist

这是从一个数据库专家那里得到的,这是我被告知的:

select 1 from `tablename`; //avoids a function call
select * from INFORMATION_SCHEMA.tables where schema = 'db' and table = 'table' // slow. Field names not accurate
SHOW TABLES FROM `db` LIKE 'tablename'; //zero rows = does not exist

显示像'table_name'这样的表

如果返回行> 0,则表存在

如果在2019年之后阅读这篇文章,请注意MySQL 5.7添加了一个table_exists过程,它将确定一个表是否存在,包括临时表。

用法: 设置@exist为",'BASE TABLE', 'VIEW', 'TEMPORARY'中的一个

CALL sys.table_exists('db1', 't3', @exists);

参考:

https://dev.mysql.com/doc/refman/5.7/en/sys-table-exists.html

性能比较:

MySQL 5.0.77,在一个大约有11000个表的数据库上。 选择一个非最近使用的表,这样它就不会被缓存。 平均每次超过10次。(注意:做不同的表,以避免缓存)。

322ms:显示'table201608'这样的表;

select 1 from table201608 limit 1;

319ms: SELECT count(*) FROM information_schema。table WHERE (TABLE_SCHEMA = 'mydb') AND (TABLE_NAME = 'table201608');

注意,如果你经常运行这个,比如在短时间内处理很多HTML请求,第2个会更快,因为它平均缓存200毫秒或更快。