有没有办法检查表是否存在而没有选择并检查它的值?
也就是说,我知道我可以去SELECT testcol FROM testtable检查返回的字段数,但似乎必须有更直接/更优雅的方式来做.
Ser*_*sev 290
你不需要算什么.
SELECT 1 FROM testtable LIMIT 1;
Run Code Online (Sandbox Code Playgroud)
如果没有错误,则表存在.
或者,如果您想要正确,请使用INFORMATION_SCHEMA.
SELECT *
FROM information_schema.tables
WHERE table_schema = 'yourdb'
AND table_name = 'testtable'
LIMIT 1;
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用 SHOW TABLES
SHOW TABLES LIKE 'yourtable';
Run Code Online (Sandbox Code Playgroud)
如果结果集中有一行,则表存在.
Mar*_*c B 62
SELECT count(*)
FROM information_schema.TABLES
WHERE (TABLE_SCHEMA = 'your_db_name') AND (TABLE_NAME = 'name_of_table')
Run Code Online (Sandbox Code Playgroud)
如果得到非零计数,则表存在.
小智 24
性能比较:
322ms: show tables like 'table201608';
691ms: select 1 from table201608 limit 1;
319ms: SELECT count(*) FROM information_schema.TABLES WHERE (TABLE_SCHEMA = 'mydb') AND (TABLE_NAME = 'table201608');
请注意,如果您正在运行这么多 - 比如在很短的时间内通过许多HTML请求 - 第二个会更快,因为它将被缓存平均200毫秒或更快.
doo*_*gle 16
您可以查询INFORMATION_SCHEMA tables系统视图:
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'databasename'
AND table_name = 'testtable';
Run Code Online (Sandbox Code Playgroud)
如果没有返回任何行,则该表不存在.
Sta*_*ler 13
阅读完以上所有内容后,我更喜欢以下陈述:
SELECT EXISTS(
SELECT * FROM information_schema.tables
WHERE table_schema = 'db'
AND table_name = 'table'
);
Run Code Online (Sandbox Code Playgroud)
它准确地指示您想要做什么,并且它实际上返回一个“布尔值”。
小智 7
这是一个不是SELECT*FROM的表
SHOW TABLES FROM `db` LIKE 'tablename'; //zero rows = not exist
Run Code Online (Sandbox Code Playgroud)
从数据库专家那里得到这个,这是我被告知的:
select 1 from `tablename`; //avoids a function call
select * from IMFORMATION_SCHEMA.tables where schema = 'db' and table = 'table' // slow. Field names not accurate
SHOW TABLES FROM `db` LIKE 'tablename'; //zero rows = not exist
Run Code Online (Sandbox Code Playgroud)
小智 5
上面的这个修改后的解决方案不需要当前数据库的明确知识。那么就更加灵活了。
SELECT count(*) FROM information_schema.TABLES WHERE TABLE_NAME = 'yourtable'
AND TABLE_SCHEMA in (SELECT DATABASE());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
243666 次 |
| 最近记录: |