我有一个mysql表,每行有20个字段。其中包括:
table: origin, destination, date, price
现在,我想删除任何仅与一组特定字段重复的行:origin, destination, date
。
我试过了:
delete from mytable where id not in
(select id from (
SELECT MAX(p.id) as id from mytable p group by p.origin, p.destination, p.date
) x)
问题:这会保留最高id
的行(表示:上次添加)。
相反,我只想保留价格最低的行。但是如何?
旁注:我无法添加唯一索引,因为该表用于LOAD DATA
的大量插入,并且不应该抛出错误。在负载时我不知道哪一行是最好的价格"之一。
此外,我不想引入任何附加或临时表复制到另一个。只需修改现有表格。
答案 0 :(得分:1)
自我加入解决方案:
delete t1
from yourtable t1
join yourtable t2
on t1.origin = t2.origin
and t1.destination = t2.destination
and t1.date = t2.date
and t1.price > t2.price
答案 1 :(得分:0)
delete t1
from mytable t1
left join
(
SELECT origin, destination, date, min(price) as price
from mytable
group by origin, destination, date
) t2 on t1.origin = t2.origin
and t1.destination = t2.destination
and t1.date = t2.date
and t1.price = t2.price
where t2.origin is null