更新MySQL表,删除旧记录。

时间:2011-02-10 22:57:09

标签: mysql sql sql-update

我有一个关联的MySQL表(user_category),用于存储用户对类别的偏好。它有一个UserId列和一个CategoryCode列。如果用户对旅行(trvl)类别和免费资料(免费)类别感兴趣,那么记录将如下所示。

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'是他们感兴趣的新类别。

3 个答案:

答案 0 :(得分:5)

有时最简单的解决方案是最好的解决方案。这是其中一次;)

答案 1 :(得分:0)

这取决于实施。如果您可以将新选择放入表结构,则此查询允许您仅删除不再有效的de首选项,并仅插入新首选项。如果您需要同时为许多用户操作批处理,它也可以工作。

-- Delete just the preferences that are no longer valid
DELETE  user_category 
from    user_category a left join
        NewSelection b on a.UserId=b.UserId and a.CategoryCode=b.CategoryCode
WHERE   b.CategoryCode is null

-- Insert just the new preferences
INSERT INTO user_category (UserId,CategoryCode) 
SELECT  a.UserId,a.CategoryCode
FROM    NewSelection a left join
        user_category b on a.UserId=b.UserId and a.CategoryCode=b.CategoryCode
where   b.CategoryCode is null

答案 2 :(得分:0)

delete from user_category where UserId = 1 and CategoryCode not in (x, y, z)
insert into user_category values (1, x) on duplicate key update CategoryCode = x

假设您的主键是UserId,CategoryCode。