1

我有一个格式为:

`users`
- id
- views
- email

以下是我的一些条目:

`id`        `email`                 `likes`
9570800   -anroy@gmail.com      888
5355388   -Btionz@gmail.com     3042
8610061   -cmendez@naia.org         450
6189810   -dancox_photog@yahoo.co.uk 0
6625684   -david.d.@gmail.com        0
16841675  -david.d.@gmail.com        40
9716153   -david.d.@gmail.com        0
9716353                              0
97161453                             0

我希望DELETE所有具有重复电子邮件的条目并保留最高的条目likes。例如,在上面,重复的 for-david.d.@gmail.com 意味着6625684并且9716153都将被删除,并且16841675将被保留(因为它在重复项中拥有最多的喜欢。

此外,如果email为空白(''NULL),忽略它/不要删除它。

我将如何完成此查询?

4

3 回答 3

2
DELETE lesser FROM MyTable AS greater JOIN MyTable AS lesser USING (email)
WHERE greater.email <> '' AND greater.likes > lesser.likes;
于 2013-03-27T03:42:39.560 回答
0
DELETE FROM Users WHERE NOT userid in (
    SELECT userid FROM Users u 
        INNER JOIN (SELECT userid,max(likes) ml FROM Users GROUP BY userid) u2
           ON u.userid = u2.userid AND u.likes = u2.ml
    )
于 2013-03-27T03:43:12.750 回答
0

首先,要小心。查看可能删除的列表:

SELECT * FROM users
INNER JOIN (
  SELECT email, max(likes) max_likes FROM users GROUP BY email HAVING count(*) > 1
) keep ON users.email = keep.email
WHERE users.likes <> keep.max_likes

然后,如果您觉得这没问题,请替换SELECT *DELETE users

于 2013-03-27T03:43:21.280 回答