Reputation: 3192
I need an update
statement to resolve some issues with duplicates in a table on MySQL. The table structure is shown below. I need a MySQL statement that will set the value of duplicate as NULL
except the first one, i.e the one with the lowest id. Here the id is the primary key.
This is an example of what I have:
id name
1 foo
2 foo
3 bar
4 NULL
5 NULL
6 foo
7 bar
This is the desired result:
id name
1 foo
2 NULL
3 bar
4 NULL
5 NULL
6 NULL
7 NULL
The table has other columns with useful information. Hence, the row can't just simply be deleted.
Upvotes: 0
Views: 148
Reputation: 3192
UPDATE t JOIN
(SELECT name, MIN(id) as min_id
FROM t
WHERE name IS NOT NULL
GROUP BY name
HAVING COUNT(*) > 1
) tt
ON t.name = tt.name and t.id > tt.min_id
SET t.name = NULL;
Upvotes: 0
Reputation: 1270463
I would write this as:
UPDATE t JOIN
(SELECT name, MIN(id) as min_id
FROM t
GROUP BY name
) tt
ON t.name = tt.name and t.id > tt.min_id
SET t.name = NULL;
I think the logic is easier to follow using JOIN
. Basically, it says to find the minimum id for each name
. Then set all other rows for the same name
to NULL
.
Upvotes: 1