MySQL删除除NULL以外的重复行

时间:2013-03-27 14:17:10

标签: php mysql sql sql-delete

我的数据库中有一个表(Final),我想删除除了
之外的所有重复行 那些有NULL值的人;
我尝试了以上内容:

 DELETE FROM Final 
  WHERE event_id NOT IN (SELECT MIN(event_id) AS MinID 
                           FROM (SELECT * FROM Final) as x 
                          GROUP BY event_name
                            AND event_name IS NOT NULL)

但没有用。

修改

我的桌子似乎是:

id |珊瑚
1 | NULL
2 | 1
3 | 1< - DELETE
4 | 2
5 | NULL< - 保持原样 6 | 1< -DELETE

2 个答案:

答案 0 :(得分:1)

加入桌子怎么样?

DELETE  a
FROM    Final a
        LEFT JOIN
        (
            SELECT  Event_name, MIN(Event_ID) MIN_ID
            FROM    Final
            WHERE   Event_name IS NOT NULL
            GROUP   BY Event_name
        ) b ON a.Event_name = b.Event_name AND
                a.Event_ID = b.MIN_ID
WHERE   a.Event_name IS NOT NULL AND 
        b.Event_name IS NULL

答案 1 :(得分:1)

只需将AND event_name IS NOT NULL部分移动到主子查询:

DELETE FROM Final 
  WHERE event_id NOT IN (SELECT MIN(event_id) AS MinID 
                           FROM (SELECT * FROM Final) as x 
                          GROUP BY event_name)
    AND event_name IS NOT NULL