# 检查内存使用情况

要在performance\_schema中启用内存监测，请启用 <mark style="color:blue;">**memory**</mark> 类的插桩。启用后就可以查看MySQL内部结构如何使用内存的详细信息。

```sql
UPDATE setup_instruments
SET enabled = 'YES'
WHERE name LIKE 'memory/%'
  AND enabled = 'NO';
```

## 直接使用performance schema

Performance Schema将内存使用统计信息存储在摘要表中，摘要表的名称以 <mark style="color:blue;">**memory\_summary\_**</mark> 前缀开头。内存使用聚合统计，其参数如下表所示：

<table><thead><tr><th width="423">聚合表</th><th>描述</th></tr></thead><tbody><tr><td><strong>memory_summary_global_by_event_name</strong></td><td>按事件名全局聚合</td></tr><tr><td><strong>memory_summary_by_thread_by_event_name</strong></td><td>按线程聚合：包括后台线程和用户线程</td></tr><tr><td><strong>memory_summary_by_account_by_event_name</strong></td><td>按用户账号聚合</td></tr><tr><td><strong>memory_summary_by_host_by_event_name</strong></td><td>按主机聚合</td></tr><tr><td><strong>memory_summary_by_user_by_event_name</strong></td><td>按用户名聚合</td></tr></tbody></table>

例如，要找到占用大部分内存的 InnoDB 结构，可以执行以下查询：

```sql
SELECT
    event_name,
    current_number_of_bytes_used / 1024 / 1024 AS current_mb,
    high_number_of_bytes_used / 1024 / 1024    AS high_mb
FROM memory_summary_global_by_event_name
WHERE event_name LIKE 'memory/innodb/%'
ORDER BY current_number_of_bytes_used DESC
LIMIT 10;
```

## 使用sys schema

使用sys schema中的视图可以更好地获取内存统计信息，可以按 host、user、thread 或 global 进行聚合。

```sql
SHOW TABLES FROM sys LIKE 'memory_%';

+---------------------------------+
|Tables_in_sys (memory_%)         |
+---------------------------------+
|memory_by_host_by_current_bytes  |
|memory_by_thread_by_current_bytes|
|memory_by_user_by_current_bytes  |
|memory_global_by_current_bytes   |
|memory_global_total              |
+---------------------------------+
```

<mark style="color:blue;">**memory\_global\_total**</mark> 视图包含一个单独的值，显示被监测内存的总量：

```sql
SELECT * FROM sys.memory_global_total;

+---------------+
|total_allocated|
+---------------+
|143.44 MiB     |
+---------------+
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://bohans.gitbook.io/ji-chu/mysql/sql-you-hua/performance-schema/shi-yong/jian-cha-nei-cun-shi-yong-qing-kuang.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
