-- 原材料送检记录测试数据重置脚本（稳妥版）
-- 作用：
-- 1) 将存在送检记录关联的原材料卡片检测结果重置为「未检(0)」
-- 2) 清空原材料送检记录主表/子表数据
SET NAMES utf8mb4;

START TRANSACTION;

-- 执行前计数（便于确认是否命中数据）
SELECT COUNT(1) AS before_record_count FROM mes_xsl_raw_material_inspect_record;
SELECT COUNT(1) AS before_record_line_count FROM mes_xsl_raw_material_inspect_record_line;

-- 回写原材料卡片检测结果为未检（0）：只重置存在送检记录关联的卡片
UPDATE mes_xsl_raw_material_card c
JOIN (
  SELECT DISTINCT r.raw_material_card_id AS card_id
  FROM mes_xsl_raw_material_inspect_record r
  WHERE r.raw_material_card_id IS NOT NULL
    AND r.raw_material_card_id <> ''
) t ON t.card_id = c.id
SET c.test_result = '0',
    c.update_time = NOW();

-- 先删子表，再删主表
DELETE FROM mes_xsl_raw_material_inspect_record_line
WHERE record_id IN (
  SELECT id FROM mes_xsl_raw_material_inspect_record
);

DELETE FROM mes_xsl_raw_material_inspect_record;

COMMIT;

-- 执行后计数
SELECT COUNT(1) AS remaining_record_count FROM mes_xsl_raw_material_inspect_record;
SELECT COUNT(1) AS remaining_record_line_count FROM mes_xsl_raw_material_inspect_record_line;
