-- 会员编号字段迁移脚本
-- 执行日期: 2025-09-26
-- 描述: 为用户表添加会员编号字段，按照创建时间从1开始递增编号

-- Step 1: 添加会员编号字段
ALTER TABLE `t_users`
ADD COLUMN `member_number` INT NULL COMMENT '会员编号（按注册时间递增）' AFTER `gender`;

-- Step 2: 创建索引以提高查询性能
CREATE INDEX `idx_member_number` ON `t_users` (`member_number`);

-- Step 3: 为现有用户按照创建时间分配会员编号（从1开始递增）
SET @row_number = 0;
UPDATE `t_users`
SET `member_number` = (@row_number := @row_number + 1)
WHERE `member_number` IS NULL
ORDER BY `created_at` ASC;

-- Step 4: 验证更新结果
SELECT
    COUNT(*) as total_users,
    MIN(member_number) as min_member_number,
    MAX(member_number) as max_member_number,
    COUNT(DISTINCT member_number) as unique_member_numbers
FROM `t_users`
WHERE `member_number` IS NOT NULL;

-- Step 5: 显示前10个用户的会员编号分配情况
SELECT
    `id`,
    `name`,
    `member_number`,
    `created_at`,
    `is_guest`
FROM `t_users`
WHERE `member_number` IS NOT NULL
ORDER BY `member_number` ASC
LIMIT 10;

-- Step 6: 检查是否有重复的会员编号（应该为0）
SELECT
    member_number,
    COUNT(*) as count
FROM `t_users`
WHERE `member_number` IS NOT NULL
GROUP BY `member_number`
HAVING COUNT(*) > 1;

-- 注意事项:
-- 1. 此脚本会为所有现有用户分配会员编号，按照创建时间排序
-- 2. 会员编号从1开始递增
-- 3. 包含游客用户也会分配编号
-- 4. 如果只希望为正式用户（非游客）分配编号，请在更新语句中添加条件: WHERE `member_number` IS NULL AND `is_guest` = 0
-- 5. 执行前请备份数据库