-- 自录业绩/账户消耗：确保唯一索引为「同录入人 + 同日 + 同渠道」。
-- 可重复执行：不存在则跳过删除；目标索引已存在则跳过添加。
--
-- 适用场景：
-- 1) 曾改为 uk_date_media（全局唯一）的环境 → 删除 uk_date_media，恢复 uk_creator_date_media
-- 2) 一直是 uk_creator_date_media 的环境 → 本脚本全部跳过，不会报 1091
-- 3) 尚无唯一索引的环境 → 直接添加 uk_creator_date_media

-- ========== 查看当前索引（可选） ==========
SELECT
    TABLE_NAME,
    INDEX_NAME,
    GROUP_CONCAT(COLUMN_NAME ORDER BY SEQ_IN_INDEX) AS COLUMNS
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
  AND TABLE_NAME IN ('zyt_personal_yeji', 'zyt_personal_account_cost')
  AND INDEX_NAME IN ('uk_date_media', 'uk_creator_date_media')
GROUP BY TABLE_NAME, INDEX_NAME
ORDER BY TABLE_NAME, INDEX_NAME;

-- ========== zyt_personal_yeji ==========
SET @sql = IF(
    (SELECT COUNT(*) FROM information_schema.STATISTICS
     WHERE TABLE_SCHEMA = DATABASE()
       AND TABLE_NAME = 'zyt_personal_yeji'
       AND INDEX_NAME = 'uk_date_media') > 0,
    'ALTER TABLE `zyt_personal_yeji` DROP INDEX `uk_date_media`',
    'SELECT ''zyt_personal_yeji: 无 uk_date_media，跳过删除'' AS message'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @sql = IF(
    (SELECT COUNT(*) FROM information_schema.STATISTICS
     WHERE TABLE_SCHEMA = DATABASE()
       AND TABLE_NAME = 'zyt_personal_yeji'
       AND INDEX_NAME = 'uk_creator_date_media') = 0,
    'ALTER TABLE `zyt_personal_yeji` ADD UNIQUE KEY `uk_creator_date_media` (`creator_id`, `yeji_date`, `media_source`)',
    'SELECT ''zyt_personal_yeji: uk_creator_date_media 已存在，跳过添加'' AS message'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- ========== zyt_personal_account_cost ==========
SET @sql = IF(
    (SELECT COUNT(*) FROM information_schema.STATISTICS
     WHERE TABLE_SCHEMA = DATABASE()
       AND TABLE_NAME = 'zyt_personal_account_cost'
       AND INDEX_NAME = 'uk_date_media') > 0,
    'ALTER TABLE `zyt_personal_account_cost` DROP INDEX `uk_date_media`',
    'SELECT ''zyt_personal_account_cost: 无 uk_date_media，跳过删除'' AS message'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @sql = IF(
    (SELECT COUNT(*) FROM information_schema.STATISTICS
     WHERE TABLE_SCHEMA = DATABASE()
       AND TABLE_NAME = 'zyt_personal_account_cost'
       AND INDEX_NAME = 'uk_creator_date_media') = 0,
    'ALTER TABLE `zyt_personal_account_cost` ADD UNIQUE KEY `uk_creator_date_media` (`creator_id`, `cost_date`, `media_source`)',
    'SELECT ''zyt_personal_account_cost: uk_creator_date_media 已存在，跳过添加'' AS message'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
