我有一张这样的表
----------------------
| idDoc | date |
----------------------
| 1 | 2018-01-20 |
| 1 | 2018-07-15 |
| 1 | 2017-07-31 |
| 1 | 2019-01-17 |
| 1 | 2019-07-30 |
| 1 | 2020-01-11 |
| 1 | 2020-07-31 |
| 1 | 2021-01-20 |
| 15 | 2018-11-31 |
| 15 | 2019-03-17 |
| 15 | 2018-05-31 |
| 15 | 2017-05-29 |
| 15 | 2019-09-20 |
| 15 | 2020-12-31 |
| 5 | 2018-01-31 |
| 5 | 2017-07-31 |
| 5 | 2018-04-23 |
| 5 | 2019-11-31 |
| 5 | 2019-12-08 |
----------------------
我想这样(通过单一查询)就像这样:
----------------------
| idDoc | date |
----------------------
| 1 | 2017-07-31 |
| 15 | 2017-05-29 |
| 5 | 2017-07-31 |
----------------------
获取的日期将始终较旧,要删除的字段将始终(具有相同的ID)所有日期都大于它。
有什么建议吗?
答案 0 :(得分:3)
如果要删除db中的数据,请尝试以下操作:
delete t1
from demo t1
join demo t2
on t1.idDoc = t2.idDoc
and t1.`date` > t2.`date`;
请在此处查看demo。
如果您想选择样本数据等记录,请尝试以下方法:
select t1.*
from demo t1
join (select idDoc, min(`date`) minDate from demo group by idDoc) t2
on t1.idDoc = t2.idDoc
and t1.`date` = t2.`minDate`;
答案 1 :(得分:1)
我会这样做:
delete t
from t join
(select t2.idDoc, min(t2.date) as mindate
from t t2
group by t2.idDoc
) t2
on t.idDoc = t2.idDoc
where t.date > t2.mindate;
答案 2 :(得分:0)
如果您可以指定更多内容,则不完全清楚您想要的内容,但您可以尝试此查询
select *
FROM mytable
WHERE 1 order by date asc group by idDoc
答案 3 :(得分:0)