如果不存在则插入新行
INSERT new row IF NOT EXISTS
Table contents:
+----+---------+-----------+
| id | title | author |
+----+---------+-----------+
| 1 | book_1 | author_1 |
| 2 | book_2 | author_2 |
| 3 | book_3 | author_3 |
+----+---------+-----------+
id
- 是唯一的并且 AUTO_INCREMENTAL
如何防止插入重复行(仅由 title
和 author
列重复)被执行?
例如,在执行时应该忽略它(因为我们已经有 'book_2','author_2'
):
INSERT INTO books (id, title, author) VALUES (NULL,'book_2','author_2');
但是这些类型的 INSERT 是允许的(因为我们还没有 'book_4','author_4'
;'book_2','author_4'
)
INSERT INTO books (id, title, author) VALUES (NULL,'book_4','author_4');
INSERT INTO books (id, title, author) VALUES (NULL,'book_2','author_4');
您应该使用 UNIQUE KEY
创建 table,例如:(fiddle1)
CREATE TABLE `books` (
id INT AUTO_INCREMENT NOT NULL,
`title` VARCHAR(60) NOT NULL,
`author` VARCHAR(60) NOT NULL,
UNIQUE KEY `unique_book` (`title`, `author`),
PRIMARY KEY(id)
);
如果 table 已经存在,您可以通过添加 UNIQUE KEY
来更改它:(fiddle2)
CREATE UNIQUE INDEX `unique_book` ON `books` (`title`, `author`);
Table contents:
+----+---------+-----------+
| id | title | author |
+----+---------+-----------+
| 1 | book_1 | author_1 |
| 2 | book_2 | author_2 |
| 3 | book_3 | author_3 |
+----+---------+-----------+
id
- 是唯一的并且 AUTO_INCREMENTAL
如何防止插入重复行(仅由 title
和 author
列重复)被执行?
例如,在执行时应该忽略它(因为我们已经有 'book_2','author_2'
):
INSERT INTO books (id, title, author) VALUES (NULL,'book_2','author_2');
但是这些类型的 INSERT 是允许的(因为我们还没有 'book_4','author_4'
;'book_2','author_4'
)
INSERT INTO books (id, title, author) VALUES (NULL,'book_4','author_4');
INSERT INTO books (id, title, author) VALUES (NULL,'book_2','author_4');
您应该使用 UNIQUE KEY
创建 table,例如:(fiddle1)
CREATE TABLE `books` (
id INT AUTO_INCREMENT NOT NULL,
`title` VARCHAR(60) NOT NULL,
`author` VARCHAR(60) NOT NULL,
UNIQUE KEY `unique_book` (`title`, `author`),
PRIMARY KEY(id)
);
如果 table 已经存在,您可以通过添加 UNIQUE KEY
来更改它:(fiddle2)
CREATE UNIQUE INDEX `unique_book` ON `books` (`title`, `author`);