information_schema,可用 SQL 直接檢索元數據。performance_schema,提供底層性能指標,但學習曲線陡峭。sys 庫將 information_schema 的結構化元數據與 performance_schema 的運行時性能數據融合,提供開箱即用的診斷視圖與工具,讓 DBA 和開發者無需編寫複雜 SQL 即可快速定位問題。
傳統寫法(悲觀):查詢 information_schema.tables。
存儲過程寫法(樂觀):嘗試 SELECT 捕獲 1146 錯誤。
sys 庫一鍵調用:
mysql> CALL table_exists('new_feature', 't1', @v_is_exists);
mysql> SELECT IF(@v_is_exists = '', 'Not exists!', @v_is_exists) AS 'result';
+-------------+
| result |
+-------------+
| Not exists! |
+-------------+
mysql> SELECT * FROM schema_unused_indexes;
+---------------+-------------+--------------+
| object_schema | object_name | index_name |
+---------------+-------------+--------------+
| new_feature | t1 | idx_log_time |
| new_feature | t1 | idx_rank2 |
+---------------+-------------+--------------+
mysql> SELECT * FROM statement_analysis
-> WHERE db='new_feature' AND full_scan = '*' AND exec_count > 10\G
輸出包含查詢文本、執行次數、延遲統計、掃描行數、排序行數、首次/最後見到時間等完整執行畫像。
mysql> SELECT * FROM statement_analysis
-> WHERE db='new_feature' AND tmp_tables > 0
-> ORDER BY tmp_tables DESC LIMIT 1\G
mysql> SELECT statement, total FROM user_summary_by_statement_type
-> WHERE `user`='root' ORDER BY total DESC LIMIT 5;
+-------------------+-------+
| statement | total |
+-------------------+-------+
| jump_if_not | 17635 |
| freturn | 3120 |
| show_create_table | 289 |
| Field List | 202 |
| set_option | 190 |
+-------------------+-------+
sys 庫是 MySQL 5.7 為運維與開發人員量身打造的「診斷工具箱」。善用其預置視圖與存儲過程,可將繁瑣的性能分析轉化為幾條簡單查詢,極大提升排查效率。建議深入閱讀官方手冊並結合實際業務場景實踐。