How to find duplicates in 2 columns not 1

后端 未结 6 870
别跟我提以往
别跟我提以往 2020-12-04 05:59

I have a MySQL database table with two columns that interest me. Individually they can each have duplicates, but they should never have a duplicate of BOTH of them having th

6条回答
  •  半阙折子戏
    2020-12-04 06:41

    this SO post helped me, but i too wanted to know how to delete and keep one of the rows... here's a PHP solution to delete the duplicate rows and keep one (in my case there were only 2 columns and it is in a function for clearing duplicate category associations)

    $dupes = $db->query('select *, count(*) as NUM_DUPES from PRODUCT_CATEGORY_PRODUCT group by fkPRODUCT_CATEGORY_ID, fkPRODUCT_ID having count(*) > 1');
    if (!is_array($dupes))
        return true;
    foreach ($dupes as $dupe) {
        $db->query('delete from PRODUCT_CATEGORY_PRODUCT where fkPRODUCT_ID = ' . $dupe['fkPRODUCT_ID'] . ' and fkPRODUCT_CATEGORY_ID = ' . $dupe['fkPRODUCT_CATEGORY_ID'] . ' limit ' . ($dupe['NUM_DUPES'] - 1);
    }
    

    the (limit NUM_DUPES - 1) is what preserves the single row...

    thanks all

提交回复
热议问题