> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-mintlify-fbfa8bee.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> MySQL 表引擎文档

# MySQL 表引擎

MySQL 引擎允许你对存储在远程 MySQL 服务器中的数据执行 `SELECT` 和 `INSERT` 查询。

<div id="creating-a-table">
  ## 创建表
</div>

```sql theme={null}
CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
(
    name1 [type1] [DEFAULT|MATERIALIZED|ALIAS expr1],
    name2 [type2] [DEFAULT|MATERIALIZED|ALIAS expr2],
    ...
) ENGINE = MySQL({host:port, database, table, user, password[, replace_query, on_duplicate_clause] | named_collection[, option=value [,..]]})
SETTINGS
    [ connection_pool_size=16, ]
    [ connection_max_tries=3, ]
    [ connection_wait_timeout=5, ]
    [ connection_auto_close=true, ]
    [ connect_timeout=10, ]
    [ read_write_timeout=300, ]
    [ enable_compression=false ]
;
```

有关 [CREATE TABLE](/zh/reference/statements/create/table) 查询的详细说明，请参阅。

表结构可以与原始 MySQL 表的结构不同：

* 列名应与原始 MySQL 表中的列名一致，但也可以只使用其中部分列，且顺序可以任意。
* 列类型可以与原始 MySQL 表中的列类型不同。ClickHouse 会尝试将值 [cast](/zh/reference/engines/database-engines/mysql#data_types-support) 为 ClickHouse 数据类型。
* [external\_table\_functions\_use\_nulls](/zh/reference/settings/session-settings#external_table_functions_use_nulls) 设置定义了如何处理 Nullable 列。默认值：1。如果为 0，表函数不会创建 Nullable 列，而是插入默认值来代替 null。这也适用于数组中的 NULL 值。

**引擎参数**

* `host:port` — MySQL 服务器地址。
* `database` — 远程数据库名称。
* `table` — 远程表名。
* `user` — MySQL 用户。
* `password` — 用户密码。
* `replace_query` — 将 `INSERT INTO` 查询转换为 `REPLACE INTO` 的标志。如果 `replace_query=1`，则会替换该查询。
* `on_duplicate_clause` — 添加到 `INSERT` 查询中的 `ON DUPLICATE KEY on_duplicate_clause` 表达式。
  示例：`INSERT INTO t (c1,c2) VALUES ('a', 2) ON DUPLICATE KEY UPDATE c2 = c2 + 1`，其中 `on_duplicate_clause` 为 `UPDATE c2 = c2 + 1`。请参阅 [MySQL documentation](https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html)，了解在 `ON DUPLICATE KEY` 子句中可以使用哪些 `on_duplicate_clause`。
  要指定 `on_duplicate_clause`，需要向 `replace_query` 参数传递 `0`。如果同时传递 `replace_query = 1` 和 `on_duplicate_clause`，ClickHouse 会引发异常。

参数也可以通过 [命名集合](/zh/concepts/features/configuration/server-config/named-collections) 传递。在这种情况下，应分别指定 `host` 和 `port`。这种方式建议在生产环境中使用。

简单的 `WHERE` 子句 (如 `=, !=, >, >=, <, <=`) 会在 MySQL 服务器上执行。

其余条件以及 `LIMIT` 采样约束仅会在对 MySQL 的查询完成后由 ClickHouse 执行。

支持多个副本，必须使用 `|` 列出。例如：

```sql theme={null}
CREATE TABLE test_replicas (id UInt32, name String, age UInt32, money UInt32) ENGINE = MySQL(`mysql{2|3|4}:3306`, 'clickhouse', 'test_replicas', 'root', 'clickhouse');
```

<div id="usage-example">
  ## 使用示例
</div>

在 MySQL 中创建表：

```text theme={null}
mysql> CREATE TABLE `test`.`test` (
    ->   `int_id` INT NOT NULL AUTO_INCREMENT,
    ->   `int_nullable` INT NULL DEFAULT NULL,
    ->   `float` FLOAT NOT NULL,
    ->   `float_nullable` FLOAT NULL DEFAULT NULL,
    ->   PRIMARY KEY (`int_id`));
Query OK, 0 rows affected (0,09 sec)

mysql> insert into test (`int_id`, `float`) VALUES (1,2);
Query OK, 1 row affected (0,00 sec)

mysql> select * from test;
+------+----------+-----+----------+
| int_id | int_nullable | float | float_nullable |
+------+----------+-----+----------+
|      1 |         NULL |     2 |           NULL |
+------+----------+-----+----------+
1 row in set (0,00 sec)
```

使用常规参数在 ClickHouse 中创建表：

```sql theme={null}
CREATE TABLE mysql_table
(
    `float_nullable` Nullable(Float32),
    `int_id` Int32
)
ENGINE = MySQL('localhost:3306', 'test', 'test', 'bayonet', '123')
```

或者使用[命名集合](/zh/concepts/features/configuration/server-config/named-collections)：

```sql theme={null}
CREATE NAMED COLLECTION creds AS
        host = 'localhost',
        port = 3306,
        database = 'test',
        user = 'bayonet',
        password = '123';
CREATE TABLE mysql_table
(
    `float_nullable` Nullable(Float32),
    `int_id` Int32
)
ENGINE = MySQL(creds, table='test')
```

从 MySQL 表中获取数据：

```sql theme={null}
SELECT * FROM mysql_table
```

```text theme={null}
┌─float_nullable─┬─int_id─┐
│           ᴺᵁᴸᴸ │      1 │
└────────────────┴────────┘
```

<div id="mysql-settings">
  ## 设置
</div>

默认设置的效率并不高，因为它们甚至不会复用连接。通过这些设置，可以提高服务器每秒可执行的查询数量。

<div id="connection-auto-close">
  ### `connection_auto_close`
</div>

允许在查询执行后自动关闭连接，即禁用连接复用。

可能的值：

* 1 — 允许自动关闭连接，因此会禁用连接复用
* 0 — 不允许自动关闭连接，因此会启用连接复用

默认值：`1`。

<div id="connection-max-tries">
  ### `connection_max_tries`
</div>

设置启用故障转移的连接池的重试次数。

可能的值：

* 正整数。
* 0 — 启用故障转移的连接池不进行重试。

默认值：`3`。

<div id="connection-pool-size">
  ### `connection_pool_size`
</div>

连接池大小 (如果所有连接都在使用中，查询会等待，直到有连接被释放) 。

可能的值：

* 正整数。

默认值：`16`。

<div id="connection-wait-timeout">
  ### `connection_wait_timeout`
</div>

等待空闲连接的超时时间 (秒)  (当已有 `connection_pool_size` 个活动连接时) ，0 表示不等待。

可能的值：

* 正整数。

默认值：`5`。

<div id="connect-timeout">
  ### `connect_timeout`
</div>

连接超时时间 (以秒为单位) 。

可能的值：

* 正整数。

默认值：`10`。

<div id="read-write-timeout">
  ### `read_write_timeout`
</div>

读写超时 (单位：秒) 。

可选值：

* 正整数。

默认值：`300`。

<div id="enable-compression">
  ### `enable_compression`
</div>

为 MySQL 协议连接启用压缩。

默认值：`false`。

此设置适用于：

* `MySQL` 表引擎；
* `MySQL` 数据库引擎；
* `mysql` 表函数；
* 用于 MySQL 集成的命名集合。

启用后，ClickHouse 会请求对此连接启用压缩。

示例：

```sql theme={null}
CREATE TABLE mysql_engine_compression
(
    id UInt32,
    name String,
    age UInt32,
    money UInt32
)
ENGINE = MySQL('mysql80:3306', 'clickhouse', 'test_table', 'root', 'password')
SETTINGS enable_compression = 1;
```

<div id="see-also">
  ## 另请参阅
</div>

* [MySQL 表函数](/zh/reference/functions/table-functions/mysql)
* [使用 MySQL 作为字典源](/zh/reference/statements/create/dictionary/sources/mysql)
