我在MySql数据库中插入多个标签,如下所示:
| id | tagname | articleid |
----------------------------
| 1 | PHP | 120 |
----------------------------
| 2 | Linux | 120 |
----------------------------
| 3 | Apache | 120 |
现在,在编辑页面中,我需要编辑标签(添加新标签-删除标签或插入/更新现有标签)。
我的方法:(有效)
第一个:我用articleid
删除所有tags
第二个:插入现有或新建/编辑tags
。
我的方法是真的和优化?!
有更好的方法吗?
您可以创建一个UNIQUE索引,该索引只允许每个标记在每篇文章中出现一次。完成后,您可以使用一个DELETE和一个INSERT IGNORE来保留已经存在的标记并添加新的标记;请注意,您只需要列出更新后的标签;
-- Done a single time for the table. Disallows duplicates
CREATE UNIQUE INDEX tag_article_uq ON mytable(tagname, articleid);
-- Items have been updated/added to add Python/Nginx and remove Apache
-- Delete all tags that aren't listed for articleid 120
DELETE FROM mytable
WHERE articleid=120 AND tagname NOT IN ('PHP', 'Linux', 'Python', 'Nginx');
-- Add the tags that don't already exist for articleid 120.
INSERT IGNORE INTO mytable (tagname, articleid) VALUES
('PHP', 120), ('Linux', 120), ('Python', 120), ('Nginx', 120);
要测试的SQLfiddle。