我有两个表(id_test,test),每个表都有一个ID列,这是唯一的,并且两个表中具有相同ID的两个条目是相同的。现在,我在一个表中的另一列(id_test)也应该是唯一的,因此我想根据另一列消除重复项,我们将其称为YD。

识别我使用的重复项

SELECT ID, YD AS x, COUNT(*) AS y
FROM id_test
GROUP BY x
HAVING y>1;


现在,我想在两个表中删除这些条目。我该怎么做?

最佳答案

此查询显示ID表中每个YD的第一个id_test

SELECT ID, YD
FROM id_test
GROUP BY YD


这些是您必须保留的行。以下查询返回您必须删除的ID:

SELECT id_test.ID
FROM id_test LEFT JOIN (select ID, YD from id_test group by YD) id_test_keep
     on id_test.ID=id_test_keep.ID and id_test.YD = id_test_keep.YD
WHERE id_test_keep.ID IS NULL


现在,我认为我需要有关您的表的更多详细信息,但是我认为您需要的是:

DELETE FROM test
WHERE
  test.ID IN (
    SELECT id_test.ID
    FROM id_test LEFT JOIN (select ID, YD from id_test group by YD) id_test_keep
         on id_test.ID=id_test_keep.ID and id_test.YD = id_test_keep.YD
    WHERE id_test_keep.ID IS NULL)

10-08 20:19