我需要删除所有重复项,并且只保留一个数量最多的副本。也许我应该做某种JOIN操作,但我不是很有经验。我有这个问题:
SELECT *
FROM invoices
GROUP BY user
ORDER BY amount DESC
它查询所有行,按金额对它们进行排序并“删除”重复项,因为它按用户分组,但显然不会删除重复项。任何帮助表示赞赏。为清楚起见,必须永久删除重复项。 架构:
user varchar(125), amount int
答案 0 :(得分:2)
如果您执行的SELECT *
不会过滤掉记录,即使使用GROUP BY
。
SELECT user, MAX(amount) amount
FROM invoices
GROUP BY user
ORDER BY amount DESC
答案 1 :(得分:1)
请注意,由于您使用GROUP BY
的方式,您将无法获得所需的结果。 MySQL extends it's functionality。您希望始终在GROUP BY
:
SELECT col1, col2, AGGREGATE(col3)
FROM table
GROUP BY col1, col2
我需要选择查找重复项的所有行
要查找每个MAX
的{{1}}金额:
user
并仅保留金额最高的行
选项1
使用SELECT user,
Max(amount) AS amount
FROM invoices
GROUP BY user
(感谢JW):
LEFT JOIN
http://sqlfiddle.com/#!2/ce2f8/1
选项2
创建一个临时表:
DELETE invoices
FROM invoices
LEFT JOIN
(SELECT user, MAX(amount) AS amount
FROM invoices
GROUP BY user) j
ON j.user = invoices.user
AND j.amount = invoices.amount
WHERE j.amount IS NULL
答案 2 :(得分:1)
为了找到重复项,您可以尝试:
SELECT id, COUNT(amount) AS cnt, MAX(amount) AS mx
FROM invoices
GROUP BY user HAVING cnt > 1
ORDER BY amount DESC
从那里,您可以继续删除这些记录。
答案 3 :(得分:0)
如果您想要金额最高的行,请尝试以下方法:
select *
from invoices
order by amount desc
limit 1
我不确定你的意思是“删除”。你真的想要删除所有行,但是要删除金额最高的行吗?