3

我需要对表运行计数查询,但前提是该表存在,

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;

如果表不存在,上述查询应返回 0,但如果存在,则应获取计数。

这会返回一个错误,说“testtable”不存在,我们知道它不存在,因为 information_schema 计数返回 0。

这在 MySQL 中可能吗?

4

1 回答 1

1

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.

于 2013-09-11T11:57:28.800 回答