在實際輸入資料庫的過程中,如果資料量比較大的話,難免會因為一些原因,而錄入多個重複的記錄,那麼應該如何操作才能刪除重複行,並且保留一條id較大,或者較小的記錄呢。
在本例中所用數據表結構如下所示tdb_goods
表中數據重複如圖所示
首先第一步,利用group by分組找出每組中數目大於2的(即重複記錄的)內容
mysql> SELECT goods_id,goods_name FROM tdb_goods GROUP BY goods_name HAVING COUN T(goods_name)>=2; +----------+------------------------------+ | goods_id | goods_name | +----------+------------------------------+ | 20 | X3250 M4机架式服务器 2583i14 | | 19 | 商务双肩背包 | +----------+------------------------------+ 2 rows in set (0.01 sec)
然後使用LEFT JOIN使原始表和上述查詢結果進行連接,刪除重複記錄,保留id較小的記錄
mysql> DELETE t1 FROM tdb_goods AS t1 LEFT JOIN( SELECT goods_id,goods_name FROM tdb_goods GROUP BY goods_name HAVING COUNT(goods_name)>=2) AS t2 ON t1.goods_na me = t2.goods_name WHERE t1.goods_id>t2.goods_id; Query OK, 2 rows affected (0.06 sec)
從上述語句可以看出,條件是名稱相同的,然後刪除所有goods_id大的記錄。這樣就可以達到想要的效果。
若想保留id較大的同理,如下所示
mysql> DELETE t1 FROM tdb_goods AS t1 LEFT JOIN( SELECT max(goods_id) AS goods_i d,goods_name FROM tdb_goods GROUP BY goods_name HAVING COUNT(goods_name)>=2) AS t2 ON t1.goods_name = t2.goods_name WHERE t1.goods_id<t2.goods_id; Query OK, 2 rows affected (0.03 sec)
注意關於錶連接,如有疑問請查看JOIN的用法。
以上就是mysql如何刪除表中的重複行並保留id較小(或較大)的記錄的內容,更多相關內容請關注PHP中文網(www.php.cn)!