我在 MySql 数据库中插入多个标签,如下所示:
| id | tagname | articleid |
----------------------------
| 1 | PHP | 120 |
----------------------------
| 2 | Linux | 120 |
----------------------------
| 3 | Apache | 120 |
现在,在编辑页面中我需要编辑标签(添加新标签 - 删除标签或插入/更新现有标签)。
我的方法:(实际操作)
首先:我删除了所有带有 articleid
的标签
第二:插入现有或新建/编辑标签
。
我的方法正确且经过优化?!
有更好的方法吗?
最佳答案
您可以创建一个 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);
关于PHP MySQL : Better Way to Update tag system,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25703412/