简体   繁体   English

MySQL 查询返回重复+原始记录?

[英]MySQL query to return duplicated + original records?

So I have a table with duplicates and i want to update the original + duplicate values in that table.所以我有一个重复的表,我想更新该表中的原始+重复值。 I can use the Update statement to update but I can't seem to figure out a query to return records that include both duplicate and original.我可以使用Update语句进行更新,但我似乎无法找出一个查询来返回包含重复和原始记录的记录。

This is the query I'm using:这是我正在使用的查询:

Select primary_id, user_number, duplicate, ignored from myTable 
group by user_number 
having count(user_number) > 1;

I have 27 unique user_number and all of them have at least 1 duplicate so I want the query to return at least 54 records (unique + duplicate) but it returns 27 records with unique only.我有 27 个唯一的 user_number 并且它们都至少有 1 个重复,所以我希望查询返回至少 54 条记录(唯一 + 重复),但它只返回 27 条唯一的记录。

Goal is to change the values in duplicate and ignored columns to 1 .目标是将重复忽略列中的值更改为1

Once i get all the records I can run the update query below:获得所有记录后,我可以运行以下更新查询:

update myTable 
set duplicate = 1, ignored = 1

primary_id is auto incremented id primary_id 是自动递增的 id

You can use joins in update statements in MySQL.您可以在 MySQL 中的更新语句中使用连接。

UPDATE myTable AS t1
JOIN myTable AS t2 ON t1.user_number = t2.user_number 
  AND t1.primary_id < t2.primary_id
SET t2.duplicate = 1, t2.ignored = 1;

This updates a duplicate row with a greater primary_id and the same user_number as the first row where that user_number occured.这将使用更大的primary_id和与该user_number出现的第一行相同的user_number更新重复行。

This naturally only affects rows that have duplicates, because if a row t1 does not have a duplicate, there will not be another row t2 for it to join to.这自然只会影响具有重复项的行,因为如果行t1没有重复项,则不会有另一行t2可供它加入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM