,你可以做這樣的事情:最初選擇
CREATE TABLE book_tag (
book_id INT(10) NOT NULL,
tag_id INT(10) NOT NULL,
modified TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (book_id,tag_id)
);
這些標籤:1 ,2,3
INSERT IGNORE INTO book_tag(book_id, tag_id) VALUES
(1,1),
(1,2),
(1,3);
/* 3 rows affected, 0 rows found. Duration for 1 query: 0.031 sec. */
一些標籤被觸發後,仍然選擇這些標籤:3,4,5,現在,這裏是你能做什麼:
ⅰ)除去所有標籤,除了所選擇的:
DELETE FROM book_tag
WHERE book_id = 1 AND tag_id NOT IN (3, 4, 5);
/* 2 rows affected, 0 rows found. Duration for 1 query: 0.047 sec. */
ⅱ)添加被選擇的所有代碼中使用INSERT IGNORE
INSERT IGNORE INTO book_tag(book_id, tag_id) VALUES
(1,3),
(1,4),
(1,5);
/* 2 rows affected, 0 rows found. Duration for 1 query: 0.016 sec. */
最終結果是:
SELECT * FROM book_tag;
/* 0 rows affected, 3 rows found. Duration for 1 query: 0.000 sec. */
book_id tag_id modified
======= ====== ===================
1 3 2011-10-27 14:06:27 -- the row inserted in the first pass
1 4 2011-10-27 14:07:04 -- the row inserted in the second pass
1 5 2011-10-27 14:07:04 -- the row inserted in the second pass
謝謝,我雖然我必須先做一個SELECT並計算需要插入的行d和需要刪除的行。你知道你的方法是否比首先刪除全部然後再次插入更快? – felixfbecker