MySQL Select If Table Exists

我是研究僧i 提交于 2019-12-17 20:27:38

问题


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.

This returns an error saying "testtable" doesn't exist, we know it doesn't exist as the information_schema count returns 0.

Is this possible in MySQL?


回答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.



来源:https://stackoverflow.com/questions/18738909/mysql-select-if-table-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!