-- ================================================
-- 系统性能诊断脚本
-- ================================================

USE study;

-- ================================================
-- 1. 检查当前正在运行的查询
-- ================================================
SELECT '检查当前运行的查询...' AS info;

SELECT 
    id,
    user,
    host,
    db,
    command,
    time AS '执行时间(秒)',
    state AS '状态',
    LEFT(info, 100) AS 'SQL语句'
FROM information_schema.processlist
WHERE db = 'study'
ORDER BY time DESC;

-- ================================================
-- 2. 检查表的索引数量（索引过多会导致INSERT/UPDATE变慢）
-- ================================================
SELECT '检查索引数量...' AS info;

SELECT 
    TABLE_NAME AS '表名',
    COUNT(DISTINCT INDEX_NAME) AS '索引数量',
    GROUP_CONCAT(DISTINCT INDEX_NAME) AS '索引列表'
FROM information_schema.STATISTICS 
WHERE TABLE_SCHEMA = 'study'
AND TABLE_NAME IN ('sys_user', 'student_class', 'sys_user_role')
GROUP BY TABLE_NAME
ORDER BY COUNT(DISTINCT INDEX_NAME) DESC;

-- ================================================
-- 3. 检查表大小和行数
-- ================================================
SELECT '检查表大小...' AS info;

SELECT 
    TABLE_NAME AS '表名',
    TABLE_ROWS AS '行数',
    ROUND(DATA_LENGTH/1024/1024, 2) AS '数据大小(MB)',
    ROUND(INDEX_LENGTH/1024/1024, 2) AS '索引大小(MB)',
    ROUND((DATA_LENGTH+INDEX_LENGTH)/1024/1024, 2) AS '总大小(MB)'
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'study'
AND TABLE_NAME IN ('sys_user', 'student_class', 'sys_user_role', 'study_class')
ORDER BY (DATA_LENGTH+INDEX_LENGTH) DESC;

-- ================================================
-- 4. 检查是否有锁表
-- ================================================
SELECT '检查表锁...' AS info;

SHOW OPEN TABLES WHERE In_use > 0;

-- ================================================
-- 5. 测试简单查询的性能
-- ================================================
SELECT '测试查询性能...' AS info;

-- 测试1：简单SELECT
SET @start_time = NOW(6);
SELECT COUNT(*) FROM sys_user;
SET @end_time = NOW(6);
SELECT TIMESTAMPDIFF(MICROSECOND, @start_time, @end_time)/1000 AS '查询耗时(ms)';

-- ================================================
-- 6. 查看慢查询日志状态
-- ================================================
SELECT '慢查询配置...' AS info;

SHOW VARIABLES LIKE 'slow_query%';
SHOW VARIABLES LIKE 'long_query_time';

-- ================================================
-- 7. 检查数据库连接数
-- ================================================
SELECT '检查连接数...' AS info;

SHOW STATUS LIKE 'Threads_connected';
SHOW STATUS LIKE 'Max_used_connections';
SHOW VARIABLES LIKE 'max_connections';

-- ================================================
-- 8. 详细查看 sys_user 表的所有索引
-- ================================================
SELECT '详细索引信息 - sys_user' AS info;

SHOW INDEX FROM sys_user;

-- ================================================
-- 9. 详细查看 student_class 表的所有索引
-- ================================================
SELECT '详细索引信息 - student_class' AS info;

SHOW INDEX FROM student_class;
