删除除最大值之外的所有行

时间:2016-04-08 16:11:18

标签: mysql sql

我将交易存储在一个表中,我想删除所有交易(按user_id分组),但金额最大的交易除外,这是一个示例表:

+----+---------+--------+
| id | user_id | amount |
+----+---------+--------+
| 1  | 1       | 10     |
+----+---------+--------+
| 2  | 1       | 20     |
+----+---------+--------+
| 3  | 1       | 30     |
+----+---------+--------+
| 4  | 2       | 50     |
+----+---------+--------+
| 5  | 2       | 100    |
+----+---------+--------+
| 6  | 3       | 2      |
+----+---------+--------+
| 7  | 3       | 4      |
+----+---------+--------+

我想要以下结果

+----+---------+--------+
| id | user_id | amount |
+----+---------+--------+
| 3  | 1       | 30     |
+----+---------+--------+
| 5  | 2       | 100    |
+----+---------+--------+
| 7  | 3       | 4      |
+----+---------+--------+

我试过

DELETE FROM `transactions`
WHERE `user_id` NOT IN (
  SELECT `user_id`
  FROM (
    SELECT MAX(`amount`) AS ts
    FROM `transactions` e
    WHERE `user_id` = `user_id`
  ) s
  WHERE ts = `transactions`.`amount`
)
ORDER BY `transactions`.`user_id` ASC

2 个答案:

答案 0 :(得分:3)

DELETE FROM `transactions`
WHERE id NOT IN 
(
    SELECT MAX(id)
    FROM `transactions`
    group by user_id
)

每个用户的内部查询分组,并为每个用户选择最高的ID。删除内部选择中除ID以外的所有记录。

答案 1 :(得分:1)

我不确定except the latest one你是什么意思所以我考虑except last record inserted因此使用了ORDER BY id DESC

DELETE FROM `transactions`
WHERE `id` NOT IN (
    SELECT `id`
    FROM `transactions`
    GROUP BY `user_id`
    ORDER BY `id` DESC
)