-- ============================================
-- 诊断 userId=1 的消息数据问题
-- 创建时间: 2026-01-27
-- ============================================

-- 1. 检查用户1是否存在
SELECT '=== 检查用户1是否存在 ===' AS step;
SELECT * FROM user WHERE id = 1;

-- 2. 检查用户1的消息数量
SELECT '=== 检查用户1的消息数量 ===' AS step;
SELECT COUNT(*) as total_messages FROM message WHERE user_id = 1 OR receiver_id = 1;

-- 3. 检查是否有异常的消息记录（NULL字段）
SELECT '=== 检查异常消息记录 ===' AS step;
SELECT * FROM message 
WHERE (user_id = 1 OR receiver_id = 1)
  AND (
    id IS NULL 
    OR user_id IS NULL 
    OR receiver_id IS NULL
    OR content IS NULL
    OR created_time IS NULL
  )
LIMIT 10;

-- 4. 检查消息表结构
SELECT '=== 检查消息表结构 ===' AS step;
DESCRIBE message;

-- 5. 查看用户1最近的消息记录
SELECT '=== 用户1最近的消息记录 ===' AS step;
SELECT * FROM message 
WHERE user_id = 1 OR receiver_id = 1
ORDER BY created_time DESC
LIMIT 10;

-- 6. 检查是否有外键约束问题
SELECT '=== 检查外键约束 ===' AS step;
SELECT 
  TABLE_NAME,
  COLUMN_NAME,
  CONSTRAINT_NAME,
  REFERENCED_TABLE_NAME,
  REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME = 'message' 
  AND REFERENCED_TABLE_NAME IS NOT NULL;

-- 7. 检查未读消息统计
SELECT '=== 检查未读消息统计 ===' AS step;
SELECT 
  receiver_id,
  COUNT(*) as unread_count
FROM message 
WHERE receiver_id = 1 AND is_read = 0
GROUP BY receiver_id;
