Mysql:The Merge Storage Engine:类【union all】联合视图存储引擎
The MERGE
storage engine, also known as the MRG_MyISAM
engine, is a collection of identical MyISAM
tables that can be used as one. “Identical” means that all tables have identical column data types and index information. You cannot merge MyISAM
tables in which the columns are listed in a different order, do not have exactly the same data types in corresponding columns, or have the indexes in different order. However, any or all of the MyISAM
tables can be compressed with myisampack. See Section 4.6.6, “myisampack — Generate Compressed, Read-Only MyISAM Tables”. Differences between tables such as these do not matter:
-
Names of corresponding columns and indexes can differ.
-
Comments for tables, columns, and indexes can differ.
-
Table options such as
AVG_ROW_LENGTH
,MAX_ROWS
, orPACK_KEYS
can differ.
An alternative to a MERGE
table is a partitioned table, which stores partitions of a single table in separate files and enables some operations to be performed more efficiently. For more information, see Chapter 23, Partitioning.
When you create a MERGE
table, MySQL creates a .MRG
file on disk that contains the names of the underlying MyISAM
tables that should be used as one. The table format of the MERGE
table is stored in the MySQL data dictionary. The underlying tables do not have to be in the same database as the MERGE
table.
You can use SELECT
, DELETE
, UPDATE
, and INSERT
on MERGE
tables. You must have SELECT
, DELETE
, and UPDATE
privileges on the MyISAM
tables that you map to a MERGE
table.
The use of MERGE
tables entails the following security issue: If a user has access to MyISAM
table t
, that user can create a MERGE
table m
that accesses t
. However, if the user's privileges on t
are subsequently revoked, the user can continue to access t
by doing so through m
.
Use of DROP TABLE
with a MERGE
table drops only the MERGE
specification. The underlying tables are not affected.
To create a MERGE
table, you must specify a UNION=(
option that indicates which list-of-tables
)MyISAM
tables to use. You can optionally specify an INSERT_METHOD
option to control how inserts into the MERGE
table take place. Use a value of FIRST
or LAST
to cause inserts to be made in the first or last underlying table, respectively. If you specify no INSERT_METHOD
option or if you specify it with a value of NO
, inserts into the MERGE
table are not permitted and attempts to do so result in an error.
The following example shows how to create a MERGE
table:
CREATE TABLE t1 ( a INT NOT NULL AUTO_INCREMENT PRIMARY KEY, message CHAR(20)) ENGINE=MyISAM; CREATE TABLE t2 ( a INT NOT NULL AUTO_INCREMENT PRIMARY KEY, message CHAR(20)) ENGINE=MyISAM; INSERT INTO t1 (message) VALUES ('Testing'),('table'),('t1'); INSERT INTO t2 (message) VALUES ('Testing'),('table'),('t2'); CREATE TABLE total ( a INT NOT NULL AUTO_INCREMENT, message CHAR(20), INDEX(a)) ENGINE=MERGE UNION=(t1,t2) INSERT_METHOD=LAST;
Column a
is indexed as a PRIMARY KEY
in the underlying MyISAM
tables, but not in the MERGE
table. There it is indexed but not as a PRIMARY KEY
because a MERGE
table cannot enforce uniqueness over the set of underlying tables. (Similarly, a column with a UNIQUE
index in the underlying tables should be indexed in the MERGE
table but not as a UNIQUE
index.)
After creating the MERGE
table, you can use it to issue queries that operate on the group of tables as a whole:
mysql> SELECT * FROM total;
+---+---------+
| a | message |
+---+---------+
| 1 | Testing |
| 2 | table |
| 3 | t1 |
| 1 | Testing |
| 2 | table |
| 3 | t2 |
+---+---------+
To remap a MERGE
table to a different collection of MyISAM
tables, you can use one of the following methods:
-
DROP
theMERGE
table and re-create it. -
Use
ALTER TABLE
to change the list of underlying tables.tbl_name
UNION=(...)It is also possible to use
ALTER TABLE ... UNION=()
(that is, with an emptyUNION
clause) to remove all of the underlying tables. However, in this case, the table is effectively empty and inserts fail because there is no underlying table to take new rows. Such a table might be useful as a template for creating newMERGE
tables withCREATE TABLE ... LIKE
.
The underlying table definitions and indexes must conform closely to the definition of the MERGE
table. Conformance is checked when a table that is part of a MERGE
table is opened, not when the MERGE
table is created. If any table fails the conformance checks, the operation that triggered the opening of the table fails. This means that changes to the definitions of tables within a MERGE
may cause a failure when the MERGE
table is accessed. The conformance checks applied to each table are:
-
The underlying table and the
MERGE
table must have the same number of columns. -
The column order in the underlying table and the
MERGE
table must match. -
Additionally, the specification for each corresponding column in the parent
MERGE
table and the underlying tables are compared and must satisfy these checks:-
The column type in the underlying table and the
MERGE
table must be equal. -
The column length in the underlying table and the
MERGE
table must be equal. -
The column of the underlying table and the
MERGE
table can beNULL
.
-
-
The underlying table must have at least as many indexes as the
MERGE
table. The underlying table may have more indexes than theMERGE
table, but cannot have fewer.NoteA known issue exists where indexes on the same columns must be in identical order, in both the
MERGE
table and the underlyingMyISAM
table. See Bug #33653.Each index must satisfy these checks:
-
The index type of the underlying table and the
MERGE
table must be the same. -
The number of index parts (that is, multiple columns within a compound index) in the index definition for the underlying table and the
MERGE
table must be the same. -
For each index part:
-
Index part lengths must be equal.
-
Index part types must be equal.
-
Index part languages must be equal.
-
Check whether index parts can be
NULL
.
-
-
If a MERGE
table cannot be opened or used because of a problem with an underlying table, CHECK TABLE
displays information about which table caused the problem.
Additional Resources
-
A forum dedicated to the
MERGE
storage engine is available at https://forums.mysql.com/list.php?93.
MERGE
tables can help you solve the following problems:
-
Easily manage a set of log tables. For example, you can put data from different months into separate tables, compress some of them with myisampack, and then create a
MERGE
table to use them as one. -
Obtain more speed. You can split a large read-only table based on some criteria, and then put individual tables on different disks. A
MERGE
table structured this way could be much faster than using a single large table. -
Perform more efficient searches. If you know exactly what you are looking for, you can search in just one of the underlying tables for some queries and use a
MERGE
table for others. You can even have many differentMERGE
tables that use overlapping sets of tables. -
Perform more efficient repairs. It is easier to repair individual smaller tables that are mapped to a
MERGE
table than to repair a single large table. -
Instantly map many tables as one. A
MERGE
table need not maintain an index of its own because it uses the indexes of the individual tables. As a result,MERGE
table collections are very fast to create or remap. (You must still specify the index definitions when you create aMERGE
table, even though no indexes are created.) -
If you have a set of tables from which you create a large table on demand, you can instead create a
MERGE
table from them on demand. This is much faster and saves a lot of disk space. -
Exceed the file size limit for the operating system. Each
MyISAM
table is bound by this limit, but a collection ofMyISAM
tables is not. -
You can create an alias or synonym for a
MyISAM
table by defining aMERGE
table that maps to that single table. There should be no really notable performance impact from doing this (only a couple of indirect calls andmemcpy()
calls for each read).
The disadvantages of MERGE
tables are:
-
You can use only identical
MyISAM
tables for aMERGE
table. -
Some
MyISAM
features are unavailable inMERGE
tables. For example, you cannot createFULLTEXT
indexes onMERGE
tables. (You can createFULLTEXT
indexes on the underlyingMyISAM
tables, but you cannot search theMERGE
table with a full-text search.) -
If the
MERGE
table is nontemporary, all underlyingMyISAM
tables must be nontemporary. If theMERGE
table is temporary, theMyISAM
tables can be any mix of temporary and nontemporary. -
MERGE
tables use more file descriptors thanMyISAM
tables. If 10 clients are using aMERGE
table that maps to 10 tables, the server uses (10 × 10) + 10 file descriptors. (10 data file descriptors for each of the 10 clients, and 10 index file descriptors shared among the clients.) -
Index reads are slower. When you read an index, the
MERGE
storage engine needs to issue a read on all underlying tables to check which one most closely matches a given index value. To read the next index value, theMERGE
storage engine needs to search the read buffers to find the next value. Only when one index buffer is used up does the storage engine need to read the next index block. This makesMERGE
indexes much slower oneq_ref
searches, but not much slower onref
searches. For more information abouteq_ref
andref
, see Section 13.8.2, “EXPLAIN Statement”.
The following are known problems with MERGE
tables:
-
In versions of MySQL Server prior to 5.1.23, it was possible to create temporary merge tables with nontemporary child MyISAM tables.
From versions 5.1.23, MERGE children were locked through the parent table. If the parent was temporary, it was not locked and so the children were not locked either. Parallel use of the MyISAM tables corrupted them.
-
If you use
ALTER TABLE
to change aMERGE
table to another storage engine, the mapping to the underlying tables is lost. Instead, the rows from the underlyingMyISAM
tables are copied into the altered table, which then uses the specified storage engine. -
The
INSERT_METHOD
table option for aMERGE
table indicates which underlyingMyISAM
table to use for inserts into theMERGE
table. However, use of theAUTO_INCREMENT
table option for thatMyISAM
table has no effect for inserts into theMERGE
table until at least one row has been inserted directly into theMyISAM
table. -
A
MERGE
table cannot maintain uniqueness constraints over the entire table. When you perform anINSERT
, the data goes into the first or lastMyISAM
table (as determined by theINSERT_METHOD
option). MySQL ensures that unique key values remain unique within thatMyISAM
table, but not over all the underlying tables in the collection. -
Because the
MERGE
engine cannot enforce uniqueness over the set of underlying tables,REPLACE
does not work as expected. The two key facts are:-
REPLACE
can detect unique key violations only in the underlying table to which it is going to write (which is determined by theINSERT_METHOD
option). This differs from violations in theMERGE
table itself. -
If
REPLACE
detects a unique key violation, it will change only the corresponding row in the underlying table it is writing to; that is, the first or last table, as determined by theINSERT_METHOD
option.
Similar considerations apply for
INSERT ... ON DUPLICATE KEY UPDATE
. -
-
MERGE
tables do not support partitioning. That is, you cannot partition aMERGE
table, nor can any of aMERGE
table's underlyingMyISAM
tables be partitioned. -
You should not use
ANALYZE TABLE
,REPAIR TABLE
,OPTIMIZE TABLE
,ALTER TABLE
,DROP TABLE
,DELETE
without aWHERE
clause, orTRUNCATE TABLE
on any of the tables that are mapped into an openMERGE
table. If you do so, theMERGE
table may still refer to the original table and yield unexpected results. To work around this problem, ensure that noMERGE
tables remain open by issuing aFLUSH TABLES
statement prior to performing any of the named operations.The unexpected results include the possibility that the operation on the
MERGE
table will report table corruption. If this occurs after one of the named operations on the underlyingMyISAM
tables, the corruption message is spurious. To deal with this, issue aFLUSH TABLES
statement after modifying theMyISAM
tables. -
DROP TABLE
on a table that is in use by aMERGE
table does not work on Windows because theMERGE
storage engine's table mapping is hidden from the upper layer of MySQL. Windows does not permit open files to be deleted, so you first must flush allMERGE
tables (withFLUSH TABLES
) or drop theMERGE
table before dropping the table. -
The definition of the
MyISAM
tables and theMERGE
table are checked when the tables are accessed (for example, as part of aSELECT
orINSERT
statement). The checks ensure that the definitions of the tables and the parentMERGE
table definition match by comparing column order, types, sizes and associated indexes. If there is a difference between the tables, an error is returned and the statement fails. Because these checks take place when the tables are opened, any changes to the definition of a single table, including column changes, column ordering, and engine alterations will cause the statement to fail. -
The order of indexes in the
MERGE
table and its underlying tables should be the same. If you useALTER TABLE
to add aUNIQUE
index to a table used in aMERGE
table, and then useALTER TABLE
to add a nonunique index on theMERGE
table, the index ordering is different for the tables if there was already a nonunique index in the underlying table. (This happens becauseALTER TABLE
putsUNIQUE
indexes before nonunique indexes to facilitate rapid detection of duplicate keys.) Consequently, queries on tables with such indexes may return unexpected results. -
If you encounter an error message similar to ERROR 1017 (HY000): Can't find file: '
tbl_name
.MRG' (errno: 2), it generally indicates that some of the underlying tables do not use theMyISAM
storage engine. Confirm that all of these tables areMyISAM
. -
The maximum number of rows in a
MERGE
table is 264 (~1.844E+19; the same as for aMyISAM
table). It is not possible to merge multipleMyISAM
tables into a singleMERGE
table that would have more than this number of rows. -
Use of underlying
MyISAM
tables of differing row formats with a parentMERGE
table is currently known to fail. See Bug #32364. -
You cannot change the union list of a nontemporary
MERGE
table whenLOCK TABLES
is in effect. The following does not work:CREATE TABLE m1 ... ENGINE=MRG_MYISAM ...; LOCK TABLES t1 WRITE, t2 WRITE, m1 WRITE; ALTER TABLE m1 ... UNION=(t1,t2) ...;
However, you can do this with a temporary
MERGE
table. -
You cannot create a
MERGE
table withCREATE ... SELECT
, neither as a temporaryMERGE
table, nor as a nontemporaryMERGE
table. For example:CREATE TABLE m1 ... ENGINE=MRG_MYISAM ... SELECT ...;
Attempts to do this result in an error:
tbl_name
is notBASE TABLE
. -
In some cases, differing
PACK_KEYS
table option values among theMERGE
and underlying tables cause unexpected results if the underlying tables containCHAR
orBINARY
columns. As a workaround, useALTER TABLE
to ensure that all involved tables have the samePACK_KEYS
value. (Bug #50646)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
2009-03-16 Oracle学习笔记:oracle的启动过程