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

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


当前回答

只是添加一个额外的方法来做它,这取决于你需要它的原因,你可以使用一个处理er_no_such_table错误:1146的处理程序,如下所示:

DELIMITER ;;
CREATE PROCEDURE `insert_in_my_table`(in my_var INT)
BEGIN
   -- Error number for table not found
   DECLARE CONTINUE HANDLER FOR 1146
   BEGIN
      -- table doesn't exists, do something...
      CREATE TABLE my_table(n INT);
      INSERT INTO my_table (n) values(my_var);
   END;
      -- table does exists, do something...
      INSERT INTO my_table (n) values(my_var);
END ;;
DELIMITER ;

其他回答

如果想要正确,请使用INFORMATION_SCHEMA。

SELECT * 
FROM information_schema.tables
WHERE table_schema = 'yourdb' 
    AND table_name = 'testtable'
LIMIT 1;

或者,您也可以使用SHOW TABLES

SHOW TABLES LIKE 'yourtable';

如果结果集中有行,则表存在。

SELECT count(*)
FROM information_schema.TABLES
WHERE (TABLE_SCHEMA = 'your_db_name') AND (TABLE_NAME = 'name_of_table')

如果得到非零计数,则表存在。

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

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

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

上述修改后的解决方案不需要明确了解当前数据库。这样就更灵活了。

SELECT count(*) FROM information_schema.TABLES WHERE TABLE_NAME = 'yourtable' 
AND TABLE_SCHEMA in (SELECT DATABASE());

我在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;
    }