<?php
/**
 The MIT License

 Copyright (c) 2007 <Tsung-Hao>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 *
 * mysql -u root DBNAME -e "SELECT id,url FROM TABLE" > sql_select_data.txt
 * php duplicates.php > delete.sql # please check delete.sql
 * mysql -u root DBNAME < delete.sql
 * mysql -u root DBNAME < "ALTER TABLE `table_name` ADD UNIQUE ( `colname`) "
 *
 * @author: Tsung <tsunghao@gmail.com> https://blog.longwin.com.tw
 * @date: 2007/12/05
 * @version: v1.00
 * @desc: https://blog.longwin.com.tw/2007/12/php_remove_duplicate_key_mysql_2007/
 */
$file 'sql_select_data.txt';
$fh fopen($file'r');

$dep = array();
$before '';
if (
$fh) {
    while (!
feof($fh)) {
        
$buffer fgets($fh4096); 
        if (
preg_match('/(\d+)\s+(.*)/'$buffer$match)) {
            
$id  $match[1];
            
$url $match[2];

            if (
trim($url) == trim($before)) {
                
// 重複的話就該砍大的值, 小的那筆留下來(小的才是先進來的, 應該是唯一值)
                
$dep[] = $id;
            }
            
$before $url;
        }

        
/*
        // 先抓個 100 筆測試一下.
        if ($i++ == 100) {
            exit;
        }
        */
    
}
}
//print_r($dep);

foreach ($dep as $key => $id) {
    echo 
"DELETE FROM TABLE WHERE pk = $id;\n";
}
?>