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

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


当前回答

如果在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

其他回答

您可以查询INFORMATION_SCHEMA,而不是依赖于错误。TABLES查看表是否存在。如果有记录,那就是存在的。如果没有记录,它就不存在。

扩展这个答案,可以进一步编写一个函数,根据表是否存在返回TRUE/FALSE:

CREATE FUNCTION fn_table_exists(dbName VARCHAR(255), tableName VARCHAR(255))
  RETURNS BOOLEAN
  BEGIN
    DECLARE totalTablesCount INT DEFAULT (
      SELECT COUNT(*)
      FROM information_schema.TABLES
      WHERE (TABLE_SCHEMA COLLATE utf8_general_ci = dbName COLLATE utf8_general_ci)
        AND (TABLE_NAME COLLATE utf8_general_ci = tableName COLLATE utf8_general_ci)
    );
    RETURN IF(
      totalTablesCount > 0,
      TRUE,
      FALSE
    );
END
;


SELECT fn_table_exists('development', 'user');

你可以这样做:

            string strCheck = "SHOW TABLES LIKE \'tableName\'";
            cmd = new MySqlCommand(strCheck, connection);
            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }
            cmd.Prepare();
            var reader = cmd.ExecuteReader();
            if (reader.HasRows)
            {                             
              Console.WriteLine("Table Exist!");
            }
            else
            {                             
              Console.WriteLine("Table does not Exist!");
            }

这是我的“去”EXISTS过程,检查临时表和正常表。此过程适用于MySQL 5.6及以上版本。@DEBUG参数是可选的。默认模式是假设的,但是可以在@s语句中连接到表。

drop procedure if exists `prcDoesTableExist`;
delimiter #
CREATE PROCEDURE `prcDoesTableExist`(IN pin_Table varchar(100), OUT pout_TableExists BOOL)
BEGIN
    DECLARE `boolTableExists` TINYINT(1) DEFAULT 1;
    DECLARE CONTINUE HANDLER FOR 1243, SQLSTATE VALUE '42S02' SET `boolTableExists` := 0;
        SET @s = concat('SELECT null FROM `', pin_Table, '` LIMIT 0 INTO @resultNm');
    PREPARE stmt1 FROM @s;
    EXECUTE stmt1;
    DEALLOCATE PREPARE stmt1;
    set pout_TableExists = `boolTableExists`; -- Set output variable
    IF @DEBUG then
        select IF(`boolTableExists`
            , CONCAT('TABLE `', pin_Table, '` exists: ', pout_TableExists)
            , CONCAT('TABLE `', pin_Table, '` does not exist: ', pout_TableExists)
        ) as result;
    END IF;
END #
delimiter ;

下面是@debug on的示例调用语句:

set @DEBUG = true;
call prcDoesTableExist('tempTable', @tblExists);
select @tblExists as '@tblExists';

变量@tblExists返回一个布尔值。

下面是一个不是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