我在MySQL中有一点问题。 这是两个表:
table1:id,value1,value2
table2:id,table1_fk
在table1中,有一些重复的行,其中value1和value2是相同的(但具有不同的id)。
我想删除table1中的重复行并保留id最高的行。
但首先我需要链接table2中的行,其中链接到副本(具有最低id),然后删除它们。
非常感谢帮助我。
到目前为止:
CREATE OR REPLACE VIEW duplicateTable1 as
SELECT *
FROM table1 t1
WHERE EXISTS (SELECT t2.id
FROM table1 t2
WHERE t1.value1= t2.value1
AND t1.value2= t2.value2
AND t1.id <> t3.id)
order by value1, value2;
CREATE OR REPLACE VIEW duplicatetable2 as
SELECT *
FROM table2 t2
WHERE t2.table_fk in (
SELECT d.id
FROM duplicateTable1 d
);
Update table2 t2
Set t2.subscription_fk = (
SELECT Max(d.id)
FROM duplicateTable1 d
where d.id=t2.subscription_fk
GROUP BY d.value1, d.value2
);
答案 0 :(得分:0)
CREATE TEMPORARY TABLE tmp
SELECT MAX(id) as id, value1, value2
FROM table1 GROUP BY value1, value2;
UPDATE table2
JOIN table1 t1 ON t1.id = table1_fk
JOIN tmp t ON t.value1 = t11.value1 AND t.value2 = t11.value2
SET table2.table1_fk = t.id;
DELETE FROM table1 WHERE id NOT IN (SELECT id FROM tmp);