2

我经常遇到的更新问题有很多关系。例如,让我们以以下三个表为例:

  • 帖子
  • 标签
  • 帖子标签

当用户创建新帖子时,他可以为帖子添加标签。帖子被保存,选定的标签通过_posts_tags_附加到它。

当用户编辑帖子(并且可能也可能不编辑标签列表)并提交表单时,我必须更新帖子的标签列表。

解决方案如下:更新帖子时,我从_posts_tags_中删除该帖子的所有标签,并插入提交的标签。

另一种解决方案是从数据库中获取帖子的所有标签,将列表与提交的列表进行比较,然后决定我们必须删除什么以及我们必须插入什么。

这两种解决方案都可能很耗时。
对于这个问题有什么更聪明的解决方案?

4

1 回答 1

0

When a post is edited and the tags are not edited (optional), then simply save the post and do nothing. Why? Cause, in the posts, tags and posts_tags table you have an autoincrement column that is your primary key. This numeric column is then the foreign key in the respective tables i.e. the tables will look like the following:

posts: id_post(PK), post_title, post_content

Tags: id_tag(PK), tag_name

posts_tags: id_post_tag(PK), id_post(FK), id_tag(FK)

PK: Primary Key FK: Foreign Key

Once you save the data in this format, you will find no need to update any dependent table as the textual data is no more used to maintain database schema and relationships. This also hastens transaction times as the database is not busy in any cascade job as Bono implied.

Then run a simple loop for all the tags in the post to check their existence against the id_post in the post_tags table and if not found then insert it. While doing this loop build a string that you will use below:

Next, run the following query:

delete from post_tags where id_post = {$id_post} and id_tag not in {$list_id_tags}

This operation minimizes database server overload by minimizing IO operations which are caused by rows being added and deleted. Your case of deleting all post_tags and then inserting all tags again would have generated large IO while this method minimizes that.

于 2012-05-15T17:38:22.790 回答