Mysql 若表不存在,则执行长查询

Mysql 若表不存在,则执行长查询,mysql,sql,database,mysql5,Mysql,Sql,Database,Mysql5,我使用的是MySQL 5.0+,如果表不存在,我会尝试执行大量命令。因此,我希望: if not exist table then 10000 line query that creates and populates the table with a lot of entries. end if 唯一的问题是我一直在搜索,到目前为止我发现MySQL不支持这样的功能 目前,我有: IF NOT EXISTS `profiles` THEN A LOT OF QUERIES; END I

我使用的是MySQL 5.0+,如果表不存在,我会尝试执行大量命令。因此,我希望:

if not exist table
then
10000 line query that creates and populates the table with a lot of entries.
end if
唯一的问题是我一直在搜索,到目前为止我发现MySQL不支持这样的功能

目前,我有:

IF NOT EXISTS `profiles`
THEN
    A LOT OF QUERIES;
END IF;
出于某种原因,它不断地给我错误,说第1行的语法是错误的


因此,我想知道是否有人对如何着手解决这个问题或如何解决这个问题有更好的想法。

您必须查询
信息模式
数据库。在以下位置找到此答案:


你可以试试类似的东西

CREATE PROCEDURE test()
BEGIN
  DECLARE tmp INT;
  DECLARE CONTINUE HANDLER FOR  1146  -- 1146 - table does not exist
  BEGIN
     -- A lot of queries
  END;
  SELECT 1 INTO tmp FROM profiles LIMIT 1; -- INTO just to prevent any output
END;

添加到bfavaretto的代码中,如果您确实有信息_schema.tables,请尝试以下操作:

IF NOT EXISTS (SELECT * FROM information_schema.tables
WHERE table_schema = 'databasename'
AND table_name = 'tablename')
do your big long create table stuff

您可以尝试以下方法:

select * from table1 where exists (select table_name from information_schema.tables where table_schema=database() and table_name = 'table1');

仅当当前数据库中存在表1时,才会出现“从表1中选择*”。这是一种避免查询不存在的表中的信息的好方法,这会导致错误。您可以在存储过程之外运行它,并且需要将“where exists…”附加到每个查询中。有关详细信息,请参阅。

这似乎不相关-OP想知道如果表不存在,如何有条件地执行其他SQL。@Alnitak,但知道表是否存在的唯一方法是查询信息\u架构。他可能正在创建一个过程,因此他可以使用我发布的查询,将
table\u name
分配给一个变量,并基于该变量进行条件检查。
select * from table1 where exists (select table_name from information_schema.tables where table_schema=database() and table_name = 'table1');