Mysql query to Remove similar looking column rows without data loss in 2nd table
I have 2 tables : companies and company_details. where company_details is connected by companies table with companyID.
I want to remove similar looking company name and keep the lowest id value incompany table and also update the companyId in the 2nd table.
Is this possible to do ? Is there any MYSQL Query that can achieve this ?
A MySQL query no, a SQL query maybe, stored procedure definitely.
There is a bit too much logic to do it with a regular SQL query but you can do it with a stored procedure.
A multi step query approach might work as well.
UPDATE company_details cd
SET companyId = (
SELECT MIN(c1.id)
FROM company c1
INNER JOIN company c2
ON c1.name = c2.name
WHERE c2.id = cd.companyId
);
Second to delete duplicates
DELETE FROM company c1
WHERE
1 < (SELECT COUNT(*) FROM company c2 WHERE c1.name = c2.name)
AND
c1.id != (SELECT MIN(c1.id) FROM company c2 WHERE c1.name = c2.name)
Thanks @MohamedTammam
I made some modification in your first query to achieve what i want but overall your query works. Thanks again.
I modified and joined table on LIKE instead of =
UPDATE company_details cd
SET companyId = (
SELECT MIN(c1.id)
FROM company c1
INNER JOIN company c2
ON c1.name LIKE CONCAT('%', c2.name, '%')
WHERE c2.id = cd.companyId
);
But Your 2nd query to delete the duplicates is giving me error near.