2014-09-06 79 views
0

我插入在MySQL数据库中的多个标签,如:现在PHP MySQL的:更好的方式来更新标签系统

| id | tagname | articleid | 
---------------------------- 
| 1 | PHP | 120 | 
---------------------------- 
| 2 | Linux | 120 | 
---------------------------- 
| 3 | Apache | 120 | 

,在编辑页面,我需要编辑标签(加入新的标签 - 删除标签或插入/更新现有标签)。

我的方法:(行动)

首先:我删除所有tagsarticleid

:插入现有的或新建/编辑tags

我的方法是真实和优化?!

有没有更好的方法?

+0

我们正在谈论数百万个一次编辑的标签,或者一次编辑3-4个标签?你确定你正在优化标签最重要/最频繁的用例吗? – 2014-09-06 18:37:30

+0

我有每篇文章最多5个标签。 – user27133 2014-09-06 18:44:24

回答

0

您可以创建一个只允许每个标签每个文章出现一次的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); 

An SQLfiddle to test with