How to find/delete duplicated records in the same row
It's possible to make a query to see if there is duplicated records in the same row?
I tried to find a solution but all I can find is to detected duplicated fields in columns, not in rows.
example, let's say I have a table with rows and items:
| id | item1 | item开发者_如何学编程2 | item3 | item4 | item5 | upvotes | downvotes |
--------------------------------------------------------------------
| 1 | red | blue | red | black | white | 12 | 5 |
So I want to see if is possible to make a query to detect the fields with the same record (in this case red) and delete them, and/or how to redesign my structure to not allow the duplicates.
Thanks.
With redesign:
You may redesign the layout to something like this:
| id | item |
With (id, item) as primary key, this will forbid having twice the same item
for a given id
.
So the data will looks like this:
| id | item |
| 1 | red |
| 1 | blue |
...
Trying to insert a | 1 | red |
again will throw an error.
Without redesign:
If you don't want to change the layout, this query will find rows in which one of the fieldX
field equals an other fieldX
of the same row:
SELECT t.id FROM (select 1) dummy
JOIN (SELECT id, item1 as item FROM table
UNION SELECT id, item2 as item FROM table
UNION SELECT id, item3 as item FROM table
UNION SELECT id, item4 as item FROM table
UNION SELECT id, item5 as item FROM table) t
GROUP BY t.id
HAVING count(*) < 5
(Assuming you have 5 of those fieldX
columns.)
This actually counts the different fieldX
values for each id
. If the count is different than the number of fields, then there is a duplicate. The query returns the ids of the rows in which there is a duplicate.
After testing you can delete rows with
DELETE FROM table WHERE id IN ( <the previous query here> )
精彩评论