I store transactions in a table, and I want to delete all transactions (grouped by a user_id) except the one with the biggest amount, here is an example table:
+----+---------+--------+
| 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 |
+----+---------+--------+
I want the following result
+----+---------+--------+
| id | user_id | amount |
+----+---------+--------+
| 3 | 1 | 30 |
+----+---------+--------+
| 5 | 2 | 100 |
+----+---------+--------+
| 7 | 3 | 4 |
+----+---------+--------+
I tried
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