5

仅使用MySQL,我正在查看是否可以仅在表是新表时运行插入语句。我成功创建了一个用户变量来查看表是否存在。问题是您不能将“WHERE”与插入语句一起使用。关于如何使它工作的任何想法?

// See if the "country" table exists -- saving the result to a variable
SELECT
    @table_exists := COUNT(*)
FROM
    information_schema.TABLES
WHERE
    TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'country';

// Create the table if it doesn't exist
CREATE TABLE IF NOT EXISTS country (
    id INT unsigned auto_increment primary key,
    name VARCHAR(64)
);

// Insert data into the table if @table_exists > 0
INSERT INTO country (name) VALUES ('Afghanistan'),('Aland Islands') WHERE 0 < @table_exists;
4

2 回答 2

6
IF @TableExists > 0 THEN
   BEGIN
       INSERT INTO country (name) VALUES ('Afghanistan'),('Aland Islands');
   END
于 2008-11-15T15:25:14.340 回答
2

使用 if 语句代替 where 子句:

http://dev.mysql.com/doc/refman/5.0/en/if-statement.html

于 2008-11-15T15:26:04.213 回答