PHP MySQL : Better Way to Update tag system

标签 php mysql

我在 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);

An SQLfiddle to test with .

关于PHP MySQL : Better Way to Update tag system,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25703412/

相关文章:

php - 如何防止包含的文件在 PHP 中生成输出?

php - 我可以从 PHP 获取文件的短 DOS 名称吗?

php - 为什么我在 PHP 中收到语法错误?

mysql - 使用子查询并具有 count(distinct) 条件的查询

MySQL CASE WHEN numb IS NULL 忽略记录 WHERE numb IS NOT NULL

PHP/MYSQL 选择一个 MAX 值并将其用作插入值

java - MySQL在动态项目驱动程序问题

javascript - PHP - 阻止攻击者在输入框中使用 javascript

mysql - 两个表通过引用表引用单个表

php - Codeigniter 模型未保存在数据库中