我有一个表格格式:
`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
。例如,在上文中,-david.d.@gmail.com
的重复项意味着6625684
和9716153
都将被删除,并且16841675
将被保留(因为它最喜欢重复。
此外,如果email
为空(''
或NULL
),请忽略它/不要删除它。
我如何完成此查询?
答案 0 :(得分:2)
DELETE lesser FROM MyTable AS greater JOIN MyTable AS lesser USING (email)
WHERE greater.email <> '' AND greater.likes > lesser.likes;
答案 1 :(得分: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
)
答案 2 :(得分: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