如何查找/删除同一行中的重复记录
可以查询同一行是否有重复记录?
我试图找到解决方案,但我能找到的只是检测列中的重复字段,而不是行中的重复字段。
例如,假设我有一个包含行和项目的表:
| id | item1 | item2 | item3 | item4 | item5 | upvotes | downvotes |
--------------------------------------------------------------------
| 1 | red | blue | red | black | white | 12 | 5 |
所以我想看看是否可以进行查询来检测具有相同记录(在本例中为红色)的字段并删除它们,和/或如何重新设计我的结构不允许重复。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通过重新设计:
您可以将布局重新设计为如下所示:
使用 (id, item) 作为主键,这将禁止给定
id
拥有两次相同的item
。因此数据将如下所示:
尝试插入
| 1 | red |
再次会抛出错误。无需重新设计:
如果您不想更改布局,此查询将查找其中一个
fieldX
字段等于同一行的另一个fieldX
的行:(假设您有 5 个
fieldX
列。)这实际上会计算每个
id
的不同fieldX
值。如果计数与字段数不同,则存在重复项。该查询返回存在重复项的行的 ID。测试后您可以删除行
With redesign:
You may redesign the layout to something like this:
With (id, item) as primary key, this will forbid having twice the same
item
for a givenid
.So the data will looks like this:
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 otherfieldX
of the same row:(Assuming you have 5 of those
fieldX
columns.)This actually counts the different
fieldX
values for eachid
. 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