选择使用不同的mysql进行更新

时间:2012-08-16 11:20:57

标签: mysql sql

我有下表:

ID, initials, surname, company, active
1, p, abc, com1, 0
2, p, abc, com1, 0
3, c, acb, com1, 0
4, c, def, com1, 0
5, c, def, com1, 0

现在我想将“姓名缩写,姓氏,公司”的重复组合更新为状态1,从而产生以下结果:

ID, initials, surname, company, active
1, p, abc, com1, 0
2, p, abc, com1, 1
3, c, acb, com1, 0
4, c, def, com1, 0
5, c, def, com1, 1

选择正在运行:

SELECT DISTINCT initials, surname, company
FROM table

我试过了,但是没有用:

UPDATE table
SET active = 1
WHERE EXISTS( SELECT DISTINCT initials, surname, company)

1 个答案:

答案 0 :(得分:7)

UPDATE table AS t
  JOIN table AS tt
    ON t.initials = tt.initials
     AND t.surname = tt.surname
     AND t.company = tt.company
     AND t.id > tt.id
SET t.active = 1;

也就是说,对于每一行,如果存在另一个id较低的行,并且具有相同的姓名,姓氏和公司,则更新它。

这是sqlfiddle