-- ============================================
-- 更新开单扣减信息表（lq_kd_deductinfo）的品项分类字段
-- ============================================
-- 说明：此脚本用于更新 lq_kd_deductinfo 表的 F_ItemCategory 字段
-- 
-- 数据来源：从关联的项目资料表（lq_xmzl）的 qt2 字段获取品项分类
-- 
-- 关联关系：
-- - lq_kd_deductinfo.F_ItemId = lq_xmzl.F_Id
-- 
-- 更新逻辑：
-- - 更新所有记录（不判断是否有效）
-- - 只更新关联的项目资料存在且qt2字段有值的记录
-- - 从 lq_xmzl.qt2 字段获取品项分类（医美/科美/生美）
-- - 如果当前 F_ItemCategory 已有值但与 lq_xmzl.qt2 不一致，也会更新为最新值

-- ============================================
-- 更新开单扣减信息表的品项分类字段
-- ============================================
UPDATE lq_kd_deductinfo deduct
INNER JOIN lq_xmzl xmzl ON deduct.F_ItemId = xmzl.F_Id
SET deduct.F_ItemCategory = xmzl.qt2
WHERE xmzl.qt2 IS NOT NULL
  AND xmzl.qt2 != ''
  AND (deduct.F_ItemCategory IS NULL 
       OR deduct.F_ItemCategory = '' 
       OR deduct.F_ItemCategory != xmzl.qt2);

-- ============================================
-- 验证更新结果
-- ============================================
-- 查看更新后的统计信息
-- SELECT 
--     F_ItemCategory AS 品项分类,
--     COUNT(*) AS 记录数
-- FROM lq_kd_deductinfo
-- GROUP BY F_ItemCategory
-- ORDER BY 记录数 DESC;

-- 查看未更新的记录数（关联的项目资料不存在或qt2为空）
-- SELECT COUNT(*) AS 未更新记录数
-- FROM lq_kd_deductinfo deduct
-- LEFT JOIN lq_xmzl xmzl ON deduct.F_ItemId = xmzl.F_Id
-- WHERE xmzl.F_Id IS NULL 
--    OR xmzl.qt2 IS NULL 
--    OR xmzl.qt2 = '';

-- 查看更新前后的对比（需要先备份数据）
-- SELECT 
--     deduct.F_Id,
--     deduct.F_ItemId,
--     deduct.F_ItemName,
--     deduct.F_ItemCategory AS 更新前分类,
--     xmzl.qt2 AS 更新后分类
-- FROM lq_kd_deductinfo deduct
-- INNER JOIN lq_xmzl xmzl ON deduct.F_ItemId = xmzl.F_Id
-- WHERE xmzl.qt2 IS NOT NULL
--   AND xmzl.qt2 != ''
--   AND (deduct.F_ItemCategory IS NULL 
--        OR deduct.F_ItemCategory = '' 
--        OR deduct.F_ItemCategory != xmzl.qt2)
-- LIMIT 100;
