gpt4 book ai didi

mysql - 以编程方式删除重复行mysql

转载 作者:行者123 更新时间:2023-11-29 15:35:42 27 4
gpt4 key购买 nike

我有一个表,该表已在某一点被截断,现在数据中有许多冲突。在这篇文章中,我重命名了数据属性,但结构保持不变:


+-----------------+-----------+------------+-------------+-----------+-------------+
| parts_total_id | parts_id | title | text | value | class |
+-----------------+-----------+------------+-------------+-----------+-------------+
| 3000 | 1001 | Sub-Total: | $2400 | 2400.0000 | part_subtotal |
| 3001 | 1001 | Discount: | $0 | 0.0000 | part_discount |
| 3002 | 1001 | Total: | $2400 | 2400.0000 | part_total |
| 5001 | 1001 | Subtotal | $3200.00 | 3200.00 | part_subtotal |
| 5002 | 1001 | Total | $3200.00 | 3200.0000 | part_total |
+-----------------+-----------+------------+-------------+-----------+-------------+

我正在尝试删除较旧的记录(3000、3001、3002),并且可以使用以下命令选择要使用“part_subtotal”和“part_total”类删除的记录,然后将它们移动到表中并运行删除基于 parts_total_id:

SELECT *
FROM parts_total
WHERE parts_total_id not in
(
SELECT max(parts_total_id)
FROM parts_total
WHERE class = 'part_total'
GROUP BY parts_id
)
AND parts_total_id not in
(
SELECT max(parts_total_id)
FROM parts_total
WHERE class = 'part_subtotal'
GROUP BY parts_id
)

我遇到的问题是我还可能需要删除具有“part_discount”类的记录 3001 - 这可能并不总是存在,但通常位于part_subtotal 和part_total 之间。

最佳答案

最终使用了以下内容以及@Nick 的评论:

CREATE TEMPORARY TABLE IF NOT EXISTS parts_total_temp AS (
SELECT *
FROM parts_total
WHERE parts_total_id not in
(
SELECT max(parts_total_id)
FROM parts_total
WHERE class = 'part_total'
GROUP BY parts_id
)
AND parts_total_id not in
(
SELECT max(parts_total_id)
FROM parts_total
WHERE class = 'part_subtotal'
GROUP BY parts_id
)
AND parts_total_id <
(
SELECT MAX(parts_total_id)
FROM parts_total p1
WHERE p1.parts_id = parts_total.parts_id
AND class = 'part_subtotal'
)
);

DELETE pt1
FROM parts_total pt1
JOIN parts_total_temp pt2 ON pt1.parts_total_id = pt2.parts_total_id;

DROP TEMPORARY TABLE IF EXISTS parts_total_temp;

关于mysql - 以编程方式删除重复行mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58262478/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com