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

也就是说,我知道我可以去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

其他回答

下面是一个不是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之前,最好先检查SQL Server数据库中是否存在该表。

USE [DB_NAME]
GO
IF OBJECT_ID('table_name', 'U') IS NOT NULL
BEGIN
PRINT 'Table exists.'
END
ELSE
BEGIN
PRINT 'Table does not exist.'
END

另外 使用sys。对象,检查SQL Server中是否存在表。

USE [DB_NAME]
GO
IF EXISTS(SELECT 1 FROM sys.Objects
WHERE Object_id = OBJECT_ID(N'table_name')
AND Type = N'U')
BEGIN
PRINT 'Table exists.'
END
ELSE
BEGIN
PRINT 'Table does not exist.'
END

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

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

或者,您也可以使用SHOW TABLES

SHOW TABLES LIKE 'yourtable';

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

在阅读了以上所有内容后,我更喜欢以下说法:

SELECT EXISTS(
       SELECT * FROM information_schema.tables 
       WHERE table_schema = 'db' 
       AND table_name = 'table'
);

它确切地指出你想做什么,它实际上返回一个'布尔'

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