更新MySQL表,删除旧记录。
我有一个关联的 MySQL 表 (user_category),用于存储用户对类别的偏好。它有一个 UserId 列和一个 CategoryCode 列。如果用户对旅行(trvl)类别和免费物品(free)类别感兴趣,那么记录将如下所示。
UserId CategoryCode
1 trvl
1 free
当用户更新其类别偏好时,更新此记录的最佳方式是什么? 我认为最简单的方法就是
DELETE FROM user_category WHERE UserId = 1;
INSERT INTO user_category (UserId,CategoryCode) VALUES (1,'catx'),(1,'catx'),(1,'catx')
“catx”是他们感兴趣的新类别。
I have an associative MySQL table (user_category) that stores users preferneces for categories. It has a UserId column and a CategoryCode column. If a user was interested in the travel(trvl) category and the free stuff(free)category then the record would look like this.
UserId CategoryCode
1 trvl
1 free
What is the best way to update this record when the user updates their category preferences?
I thought the easiest way would be to just
DELETE FROM user_category WHERE UserId = 1;
INSERT INTO user_category (UserId,CategoryCode) VALUES (1,'catx'),(1,'catx'),(1,'catx')
Where 'catx' are the new categories that they are interested in.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有时,最简单的解决方案就是最好的解决方案。这就是其中之一;)
Some times easiest solutions are the best ones. And this is one of this times ;)
这取决于实施。如果您可以将新选择放入表结构中,则此查询允许您仅删除不再有效的首选项并仅插入新首选项。如果您需要同时为多个用户进行批量操作,它也适用。
It depends on the implementation. If you can put the new selection a Table structure, this query allows you to delete just de preferences that are no longer valid and insert just the new preferences. It also works if you need to operate batch for many users at the same time.
假设您的主键是 UserId、CategoryCode。
Assume that your primary key is UserId, CategoryCode.