Mysql删除重复记录但保留包含最多值的行

时间:2018-03-02 03:26:46

标签: mysql

如果我有下表:

main()

如何删除电子邮件中的重复记录库,但保留包含最多值的记录并给出以下结果?

+------+--------+---------+-------+-------+
| id   | name   | Surnmae | email |address|
+------+--------+---------+-------+-------+
| 1    |        | Lee     | aaa   |23 a st|
| 2    | a      |         | aaa   |       |
| 3    | c      |         | ccc   |       |
+------+--------+---------+-------+-------+

2 个答案:

答案 0 :(得分:0)

我有办法,但它很好,很愚蠢,它适用于小桌子,就像我上面提供的那样:

DELETE FROM table1
 WHERE firstname NOT IN (SELECT * 
                    FROM (SELECT MAX(n.firstname)
                            FROM table1 n
                        GROUP BY n.email) x) 
OR lastname NOT IN (SELECT * 
                    FROM (SELECT MAX(n.lastname)
                            FROM table1 n
                        GROUP BY n.email) x)
OR address NOT IN (SELECT * 
                    FROM (SELECT MAX(n.address)
                            FROM table1 n
                        GROUP BY n.email) x)

但有没有人有一个可以简化我的查询的想法?像一行查询?

答案 1 :(得分:-1)

请尝试这个我假设你的表名是成员

delete t1 from  members LEFT JOIN members t1 ON members.email = t1.email AND  members.id != t1.id  AND IFNULL(CHAR_LENGTH(members.Surnmae ),0) > IFNULL(CHAR_LENGTH(t1.Surnmae ),0) WHERE t1.id > 0;