How do I detect if a table exist? MySql

前端 未结 2 1523
终归单人心
终归单人心 2020-12-21 14:55

I was suggested to do this

SELECT table_schema, table_name FROM information_schema.tables
WHERE table_schema = \'mydb\' AND table_name=\'ApprovePost\';


        
相关标签:
2条回答
  • 2020-12-21 15:46

    If your only actual problem now is recreating the foreign key constantly (aside from a possibly broken MySQL install considering your other troubles), why not:

    1) give it a constraint symbol (should be unique in database) and let the adding fail silently / catch 'em?

    ALTER TABLE tbl ADD CONSTRAINT only_one_please FOREIGN KEY (columnname) ...
    

    2) or better yet, add the foreign key clause in your create table in the first place?

    As for the original question: I know no reason why this should happen, and I cannot recreate it. Selecting from information_schema is afaik quite the preferred way of checking this, and hasn't failed me yet. Aside from a brute force check like SELECT * FROM tablename LIMIT 0; and checking for errors, you first might want to check for any other caching mechanisms besides MySQL's query cache, and if they're not there / not the problem, perhaps try a SELECT SQL_NO_CACHE table_schema, table_name FROM information_schema.tables.

    0 讨论(0)
  • 2020-12-21 15:52

    Looks like you need to use the FLUSH TABLES command for the INFORMATION_SCHEMA.TABLES to reflect existing tables.

    Reference:

    • TABLE CACHE
    0 讨论(0)
提交回复
热议问题