-- ====================================
-- 深度调试：找出导致Data truncation的具体数据
-- ====================================

-- 1. 检查xq_client_log表的latitude字段定义
SELECT 
    COLUMN_NAME,
    DATA_TYPE,
    CHARACTER_MAXIMUM_LENGTH,
    COLUMN_TYPE
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_SCHEMA = DATABASE() 
AND TABLE_NAME = 'xq_client_log'
AND COLUMN_NAME = 'latitude';

-- 2. 检查iot_device_data表中项圈设备的所有字段长度
SELECT 
    device_id,
    voltage,
    temperature,
    latitude,
    longitude,
    steps,
    same_day_steps,
    server_device_id,
    LENGTH(CAST(voltage AS CHAR)) as voltage_len,
    LENGTH(CAST(temperature AS CHAR)) as temp_len,
    LENGTH(latitude) as lat_len,
    LENGTH(longitude) as lng_len,
    LENGTH(CAST(steps AS CHAR)) as steps_len,
    LENGTH(CAST(same_day_steps AS CHAR)) as same_day_steps_len,
    LENGTH(server_device_id) as server_id_len,
    HEX(latitude) as lat_hex,
    HEX(longitude) as lng_hex
FROM iot_device_data 
WHERE device_type = 4 
ORDER BY LENGTH(latitude) DESC
LIMIT 10;

-- 3. 检查是否有任何字段长度超过200
SELECT 
    device_id,
    CASE 
        WHEN LENGTH(CAST(voltage AS CHAR)) > 200 THEN CONCAT('voltage:', LENGTH(CAST(voltage AS CHAR)))
        WHEN LENGTH(CAST(temperature AS CHAR)) > 200 THEN CONCAT('temperature:', LENGTH(CAST(temperature AS CHAR)))
        WHEN LENGTH(latitude) > 200 THEN CONCAT('latitude:', LENGTH(latitude))
        WHEN LENGTH(longitude) > 200 THEN CONCAT('longitude:', LENGTH(longitude))
        WHEN LENGTH(server_device_id) > 200 THEN CONCAT('server_device_id:', LENGTH(server_device_id))
        ELSE 'OK'
    END as field_issue,
    voltage,
    temperature,
    latitude,
    longitude,
    server_device_id
FROM iot_device_data 
WHERE device_type = 4 
AND (
    LENGTH(CAST(voltage AS CHAR)) > 200 OR
    LENGTH(CAST(temperature AS CHAR)) > 200 OR
    LENGTH(latitude) > 200 OR
    LENGTH(longitude) > 200 OR
    LENGTH(server_device_id) > 200
);

-- 4. 尝试插入第9条数据（错误信息提到row 9）
SELECT 
    device_id,
    voltage,
    temperature,
    latitude,
    longitude,
    steps,
    same_day_steps,
    server_device_id,
    ROW_NUMBER() OVER (ORDER BY update_time DESC) as row_num
FROM iot_device_data 
WHERE device_type = 4 
ORDER BY update_time DESC
LIMIT 10;

-- 5. 检查第9条数据的具体内容
WITH ranked_data AS (
    SELECT 
        device_id,
        voltage,
        temperature,
        latitude,
        longitude,
        steps,
        same_day_steps,
        server_device_id,
        ROW_NUMBER() OVER (ORDER BY update_time DESC) as row_num
    FROM iot_device_data 
    WHERE device_type = 4 
    ORDER BY update_time DESC
)
SELECT 
    device_id,
    voltage,
    temperature,
    latitude,
    longitude,
    steps,
    same_day_steps,
    server_device_id,
    LENGTH(latitude) as lat_len,
    LENGTH(longitude) as lng_len,
    HEX(latitude) as lat_hex,
    HEX(longitude) as lng_hex
FROM ranked_data 
WHERE row_num = 9;
