有没有一种方法来检查表是否存在,而不选择和检查它的值?
也就是说,我知道我可以去SELECT testcol FROM testtable并检查返回字段的计数,但似乎必须有一个更直接/优雅的方式来做到这一点。
有没有一种方法来检查表是否存在,而不选择和检查它的值?
也就是说,我知道我可以去SELECT testcol FROM testtable并检查返回字段的计数,但似乎必须有一个更直接/优雅的方式来做到这一点。
当前回答
如果存在则返回1,不存在则返回0。
set @ret = 0;
SELECT 1 INTO @ret FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'my_table';
SELECT @ret;
可以放入mysql函数中
DELIMITER $$
CREATE FUNCTION ExistTable (_tableName varchar(255))
RETURNS tinyint(4)
SQL SECURITY INVOKER
BEGIN
DECLARE _ret tinyint;
SET _ret = 0;
SELECT
1 INTO _ret
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = _tablename LIMIT 1;
RETURN _ret;
END
$$
DELIMITER ;
并称之为
Select ExistTable('my_table');
如果存在则返回1,如果不存在则返回0。
其他回答
上述修改后的解决方案不需要明确了解当前数据库。这样就更灵活了。
SELECT count(*) FROM information_schema.TABLES WHERE TABLE_NAME = 'yourtable'
AND TABLE_SCHEMA in (SELECT DATABASE());
显示像'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
你可以这样做:
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!");
}
下面是一个不是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