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;

That is, for each row, update it if there exists another row with a lower id, with the same initials, surname, and company.

Here's an sqlfiddle for it.

于 2012-08-16T11:25:12.253 に答える