How to find/delete duplicated records in the same row

拜拜、爱过 提交于 2019-12-24 06:36:12

问题


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 | item2 | 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.


回答1:


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


来源:https://stackoverflow.com/questions/4773201/how-to-find-delete-duplicated-records-in-the-same-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!