开发者

Deleting and updating tags in mysql using php

If you have the following table structure:

item: id, content ect
item_tags: item_id, tag_id
tags: id, name

Where one item can have many tags.

I use the following code to select tags belonging to a certain item:

SELECT GROUP_CONCAT( DISTINCT tag.name
ORDER BY tag.name DESC
SEPARATOR ',' ) AS tags
FROM item_tags
JOIN tag ON item_tags.tag_id = tag.id
WHERE item_id =1

What strategies [*] would you use to update tags for a certain item?

I though of doing the following:

  1. Get tags from the database as original_tags
  2. Get user update of tags as changed_tags
  3. Delete all tags belonging to this item from the database
  4. find the difference between changed_tags and original_tags and add these to the database.

Looking at each tag for a particular item and seeing if one more has been added, one has been taken away, or if spelling has been changed, seems too complicated, hence the rationale to delete them all and add new tags for th开发者_JAVA技巧is item.

What thinks you?

* I'm not looking for actual code -- though that would be nice


I'm doing this in a CF setup so I can't give you a relevant code example. But here's my steps:

 1. Get all the tags from the DB for the item in question
 2. Put all the tags the user entered into an array
 3. Loop on all the tags from the DB
 4. Sub Loop on all the user supplied tags
  4a. if there is a match then remove that tag from the user supplied array, 
  4b. if no match after going through the whole subloop delete the tag.
 5. Loop what is left in the user supplied array inserting them into the DB

Note: If I find a match I break out of the sub loop and move on to the next parent loop item to save processing.


I think you don't need to retrieve original tags at all. You can issue REPLACE or INSERT ... ON DUPLICATE KEY UPDATE query to synchronize tags you receive with tags in database. Then, you need to delete all tags that are not in a new list (if all tags which are not in changed_tags list are supposed to be deleted) or tags marked for removing (if tags in changed_tags has a flag for removing).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜