我需要删除所有重复项,只保留一个数量最多的。也许我应该做一些 JOIN 操作,但我对 . 我有这个查询:
SELECT *
FROM invoices
GROUP BY user
ORDER BY amount DESC
它查询所有行,按数量对它们进行排序,并在按用户分组时“删除”重复项,但显然不会删除重复项。任何帮助表示赞赏。为了清楚起见,必须永久删除重复项。架构:
user varchar(125), amount int
我需要删除所有重复项,只保留一个数量最多的。也许我应该做一些 JOIN 操作,但我对 . 我有这个查询:
SELECT *
FROM invoices
GROUP BY user
ORDER BY amount DESC
它查询所有行,按数量对它们进行排序,并在按用户分组时“删除”重复项,但显然不会删除重复项。任何帮助表示赞赏。为了清楚起见,必须永久删除重复项。架构:
user varchar(125), amount int
如果您这样做SELECT *
,即使使用GROUP BY
.
SELECT user, MAX(amount) amount
FROM invoices
GROUP BY user
ORDER BY amount DESC
请注意,由于您使用GROUP BY
. MySQL扩展了它的功能。您希望始终指定在 中选择的列GROUP BY
:
SELECT col1, col2, AGGREGATE(col3)
FROM table
GROUP BY col1, col2
我需要选择所有行找到重复项
要找到MAX
每个的金额user
:
SELECT user,
Max(amount) AS amount
FROM invoices
GROUP BY user
并只保留金额最高的行
选项1
使用LEFT JOIN
(感谢 JW):
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
http://sqlfiddle.com/#!2/ce2f8/1
选项 2
创建临时表:
CREATE TABLE invoices (
user int,
amount decimal(5,2));
INSERT INTO invoices VALUES
(1, 100.00),
(1, 200.00),
(1, 300.00);
CREATE TABLE invoicesStg (
user int,
amount decimal(5,2));
INSERT INTO invoicesStg
(SELECT user, MAX(amount) AS amount
FROM invoices
GROUP BY user);
TRUNCATE invoices;
INSERT INTO invoices
SELECT user, amount
FROM invoicesStg;
DROP TABLE invoicesStg;
为了查找重复项,您可以尝试:
SELECT id, COUNT(amount) AS cnt, MAX(amount) AS mx
FROM invoices
GROUP BY user HAVING cnt > 1
ORDER BY amount DESC
从那里,您可以继续删除这些记录。
如果您想要金额最高的行,请尝试以下操作:
select *
from invoices
order by amount desc
limit 1
我不确定您所说的“删除”是什么意思。您真的要删除除数量最多的行之外的所有行吗?