MySQL 如果 table 不存在则创建,仅当 table 已创建时才插入记录

MySQL create table if not exists and insert record only if table was created

我需要创建一个 table 并仅在刚创建 table 时插入第一条记录。

我确实使用以下语句创建了 table:

CREATE TABLE IF NOT EXISTS tableName (
    id int(9) NOT NULL, 
    col1 int(9) DEFAULT NULL, 
    col2 int(3) unsigned zerofill DEFAULT NULL,
    PRIMARY KEY(id)
)  ENGINE = InnoDB DEFAULT CHARSET = latin1;

如何仅在刚刚创建 table 时插入第一条记录?

将创建和插入合并为一条语句:

CREATE TABLE IF NOT EXISTS tableName (
    id int(9) NOT NULL, 
    col1 int(9) DEFAULT NULL, 
    col2 int(3) unsigned zerofill DEFAULT NULL,
    PRIMARY KEY(id)
)  ENGINE = InnoDB DEFAULT CHARSET = latin1
AS SELECT 1 AS id, 10 AS col1, 5 AS col2;

如果它没有创建 table,AS SELECT ... 子句将被忽略。

这是使用 INSERT IGNORE 命令而不是 INSERT 命令的好地方。

INSERT IGNORE INTO mytable (id, field1, field2) VALUES(1, 'foo', 'bar');

来自 the mysql documentation :

Errors that occur while executing the INSERT statement are ignored. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row is discarded and no error occurs. Ignored errors generate warnings instead.