开发者

find mySQL duplicates and edit their specific fields

开发者 https://www.devze.com 2023-03-13 17:40 出处:网络
I have a table where the important fields are CompanyName and CompanyID.Right now there are a lot of rows with identical CompanyNames, but their CompanyIDs are unique.What I want to do is find all 开发

I have a table where the important fields are CompanyName and CompanyID. Right now there are a lot of rows with identical CompanyNames, but their CompanyIDs are unique. What I want to do is find all 开发者_如何转开发rows with exact CompanyNames and take one of their CompanyIDs (doesn't matter which) and apply it to all duplicates. I'm using this code to find all duplicates:

SELECT  `CompanyName` , COUNT(  `CompanyName` ) AS NumOccurrences
FROM  `product_tbl` 
GROUP BY  `CompanyName` 
HAVING (
COUNT(  `CompanyName` ) >1
)

What do I need to add to accomplish what I want to do?


This should work:

UPDATE `product_tbl` `PA`,
(
    SELECT `CompanyName`, `CompanyID`
    FROM `product_tbl`
    GROUP BY `CompanyName`
) `PB`
SET `PA`.`CompanyID` = `PB`.`CompanyID`
WHERE `PA`.`CompanyName` = `PB`.`CompanyName`;
0

精彩评论

暂无评论...
验证码 换一张
取 消