我有一张名叫tracking_history的桌子。在本表中将存储包裹跟踪历史记录。由于某些原因,当checkTrackStatus函数执行时,所有现有的跟踪状态都会重复插入到表中。这是跟踪状态序列。'ACCEPTED','AT_SENDING_DEPOT','ON_THE_ROAD','AT_DELIVERY_DEPOT','DELIVERED'
我正在保存跟踪id,order id也在那个表中。因此,我需要对每一个订单id,最新的跟踪状态应该在那里('ACCEPTED','AT_SENDING_DEPOT','ON_THE_ROAD','AT_DELIVERY_DEPOT','DELIVERED'
),剩余的重复值应该被删除。我尝试了下面的查询。
`DELETE t1 FROM tracking_history t1, tracking_history t2
WHERE t1.id < t2.id AND t1.order_id = t2.order_id`
但是,此查询只保存最新记录,并删除其余所有其他记录。Means I am having all orders ids with DELIVERED Status only.
如何通过保留最新状态来实现删除重复状态?任何帮助都将不胜感激。
发布于 2020-12-12 13:08:05
我希望在插入行时保留第一个id,而不是最后一个id。这是因为可能有用的其他信息--特别是插入时间和谁做的插入。为此,我将保留每一状态一行,但将逻辑表述为:
delete th
from tracking_history th join
(select order_status, status, min(id) as min_id
from tracking_history th2
group by order_status, status
) th2
using (order_status, status)
where id > min_id;
话虽如此,这似乎还是不对。毕竟,多行的状态可能是相同的。例如,可以多次尝试将包从仓库移动到某个地址。您真正想要的是tracking_history
中每批最新的状态。我不知道你是否有某种“批次身份”。但让我假设,有什么东西,可能是一个开始日期,把所有共同的价值观联系在一起。
在这种情况下,您需要每个“批”的最新状态:
delete th
from tracking_history th join
(select order_status, entry_date, max(id) as max_id
from tracking_history th2
group by order_status, entry_date
) th2
using (order_status, entry_date)
where id < min_id;
发布于 2020-12-12 10:36:36
您需要一个关于状态的附加关联子句:
DELETE t1
FROM tracking_history t1
INNER JOIN tracking_history t2
ON t1.id < t2.id
AND t1.order_id = t2.order_id
AND t1.status = t2.status
我建议进一步更改查询如下:
DELETE t1
FROM tracking_history t1
INNER JOIN (
SELECT order_id, status, MAX(id) as id
FROM tracking_history
GROUP BY order_id, status
) t2
ON t1.id < t2.id
AND t1.order_id = t2.order_id
AND t1.status = t2.status
这种方法的优点是每一行只匹配一次,而不是原始查询,这可能会尝试删除同一行不止一次。因此,这样做更有效率--而且在某种程度上更安全。
https://stackoverflow.com/questions/65263443
复制相似问题