小编典典

选择使用不同的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)

阅读 148

收藏
2021-05-16

共1个答案

小编典典

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

2021-05-16