sql: select 如果 table 存在

sql: select if table exists

如果 db.table 存在,我正在尝试 select 来自 db.table 的全部。我已经尝试过 if、exists 等,并且 none 有效。最好的方法是什么?我正在使用 cockroachdb 和 psycopg2。没有找到现有的答案(大多数都很旧) 我可以使用。例如,这个对我不起作用:SQl select all if table exists

我根据 Tim 的建议尝试了以下方法,但似乎不起作用。但是,db.table 存在。

 select exists (select 1 from information_schema.tables where table_name = 'table')                                                                          ;
  exists  
+--------+
  false   
(1 row)

Time: 6.848579ms

select exists (select 1 from information_schema.tables where table_name = 'db.table')                                                                      ;
  exists  
+--------+
  false   
(1 row)

Time: 5.958707ms

您可以分两步处理。首先,检查 table 是否存在于您的 Postgres 数据库中,如果存在,则 select 所有记录:

sql = "SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = %s"
cur.execute(sql, ('your_table',))
if cur.fetchone()[0]:
    sql_all = "SELECT * FROM your_table"
    cur = connection.cursor()    # get a new cursor
    cur.execute(sql_all)
    # process result set etc.