I have a MySQL tag-mapping table with structure from the following post – Recommended SQL database design for tags or tagging
I have two columns – TagID and ItemID. I want to make an update on some item (change it’s tags). For example I had item with ID=1 with tagID’s 1,2,3. But on update user want’s only tags with ID’s 3,4,5. Obviously I have to remove the “1” and “2”, keep the “3” and add “4” and “5”.
What’s the simplest way/most elegant to do it (use INSERT INGORE’S, ON DUPLICATE UPDATE or some other “features” of MySQL)?
Delete all and insert all “new” tags back or go through them all and delete/insert separately? It will be min 1, max 5 tags. Or it really doesn’t matter for such a small number of tags/operations?
If you definitely have a maximum of five tags, including them in the table as tag1, tag2, tag3, tag4, tag5 will definitely be “simplest”. For extra simplicity, you could just update all 5 values, so tags 3,4,5 are saved to tag1,tag2,tag3, with tag4 and tag5 saved as NULL. Obviously it’s not scalable – you definitely wouldn’t want to do that with a large number (or potentially unlimited) tags.
The next simplest would be to delete all and reinsert, but it’s not particularly elegant.
The most elegant way I can think of is to run two queries. The first will remove everything that is not your new set of tags. I have extended your example to show adding two replacement tags:
(3,4,5,6,7).The next will insert all of your new tags, but will ignore duplicates, based on a UNIQUE combined index of TagID and ItemID.