删除重复的条目:删除具有2个相同列的条目

时间:2013-05-03 02:35:15

标签: php mysql sql pdo

我的这张桌子名为 bag

+--------+----------+---------+----------+
| bag_id | chara_id | item_id | item_qty |
+--------+----------+---------+----------+
|      1 |        1 |       2 |       22 |
|      2 |        1 |       1 |       55 |
|      3 |        3 |       1 |        2 |
|      6 |        3 |       4 |        2 |
|      7 |        4 |       4 |        2 |
|      8 |        5 |       4 |        2 |
|      9 |        6 |       4 |        2 |
|     10 |        1 |       5 |        1 |
|     11 |        1 |       2 |        1 |
|     12 |        1 |       2 |        1 |
|     13 |        1 |       2 |        1 |
|     14 |        1 |       8 |        1 |
|     15 |        1 |       6 |        1 |
|     16 |        1 |       8 |        1 |
|     17 |        1 |       6 |        1 |
+--------+----------+---------+----------+

关系变为1 chara =很多项目 现在我不想要1个chara =许多重复的项目。

如何进行删除重复值的查询? 像chara_id:1有3个重复的item_id:2 我想删除其他2。

2 个答案:

答案 0 :(得分:2)

不是最好的方法。但下面肯定会有效:

Delete from Bag 
where bag_id 
         not in (
                 select min(bag_id) from bag a, 
                    (select chara_id, item_id 
                        from bag group by chara_id, item_id 
                            having count(*) > 1) b 
                 where a.chara_id = b.chara_id and a.item_id = b.item_id 
                 UNION
                 select bag_id from bag a, 
                    (select chara_id, item_id 
                        from bag group by chara_id, item_id 
                            having count(*) = 1) b 
                 where a.chara_id = b.chara_id and a.item_id = b.item_id
         ) 

答案 1 :(得分:1)

您可以简单地将表格bag与子查询结合使用,该子查询为bag_idchara_ID的每个组合获得最低item_ID。在子查询的任何字段上具有空值的记录是将被删除的记录。

DELETE  a
FROM    bag a
        LEFT JOIN
        (
            SELECT  chara_ID, item_ID, MIN(bag_ID) min_ID
            FROM    bag
            GROUP   BY chara_ID, item_ID
        ) b ON  a.bag_ID = b.min_ID AND
                a.chara_ID = b.chara_ID AND
                a.item_ID = b.item_ID
WHERE   b.min_ID IS NULL