1

我有下表:

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)
4

1 回答 1

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

于 2012-08-16T11:25:12.253 回答