[英]MySQL Select If Table Exists
I need to run a count query on a table but only if that table exists, 我需要在一个表上运行一个计数查询,但只有当该表存在时,
SELECT
CASE WHEN (SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'DATABASENAME' AND TABLE_NAME = 'testtable') < 1 THEN '0'
ELSE (SELECT COUNT(*) FROM testtable) END;
The above query should return 0 if the table doesn't exist, but if it does it should get the count. 如果表不存在,上面的查询应该返回0,但如果它存在,它应该得到计数。
This returns an error saying "testtable" doesn't exist, we know it doesn't exist as the information_schema count returns 0. 这返回一个错误,说“testtable”不存在,我们知道它不存在,因为information_schema count返回0。
Is this possible in MySQL? 这在MySQL中可行吗?
You can try this : 你可以试试这个:
SET @val := CASE (SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'DATABASENAME' AND TABLE_NAME = 'testtable')
WHEN 0 THEN 0
ELSE (SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'DATABASENAME' AND TABLE_NAME = 'testtable')
END;
SELECT @val;
It will return 0, if there is no such table and if such table exists , it will return the count, it may be better if you take it into function. 它将返回0,如果没有这样的表,并且如果存在这样的表,它将返回计数,如果你将它带入函数可能会更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.