SQL - 如何进行条件INSERT

Mat*_*att 5 mysql sql insert

使用MySQL,我知道如果表是新的,是否可以运行insert语句.我成功创建了一个用户变量来查看该表是否存在.问题是你不能使用"WHERE"和insert语句.关于如何使这个工作的任何想法?

// 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;
Run Code Online (Sandbox Code Playgroud)

Fly*_*wat 6

IF @TableExists > 0 THEN
   BEGIN
       INSERT INTO country (name) VALUES ('Afghanistan'),('Aland Islands');
   END
Run Code Online (Sandbox Code Playgroud)