-- 为xq_client_log表添加device_id字段
-- 解决SQLSyntaxErrorException: Unknown column 'device_id' in 'field list'错误

-- 检查字段是否已存在，如果不存在则添加
SET @sql = (SELECT IF(
    (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS 
     WHERE TABLE_SCHEMA = DATABASE() 
     AND TABLE_NAME = 'xq_client_log' 
     AND COLUMN_NAME = 'device_id') > 0,
    'SELECT "device_id字段已存在" as message',
    'ALTER TABLE xq_client_log ADD COLUMN device_id varchar(50) NOT NULL COMMENT "项圈编号" AFTER id'
));

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 为device_id字段添加索引
SET @sql2 = (SELECT IF(
    (SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS 
     WHERE TABLE_SCHEMA = DATABASE() 
     AND TABLE_NAME = 'xq_client_log' 
     AND INDEX_NAME = 'idx_device_id') > 0,
    'SELECT "device_id索引已存在" as message',
    'ALTER TABLE xq_client_log ADD INDEX idx_device_id (device_id)'
));

PREPARE stmt2 FROM @sql2;
EXECUTE stmt2;
DEALLOCATE PREPARE stmt2;

-- 显示表结构确认
DESCRIBE xq_client_log;
