6.12.多服務器復制中的Auto-Increment
6.12. 多服務器復制中的Auto-Increment
當將多個服務器配置為復制主服務器時,使用auto_increment時應采取特殊步驟以防止鍵值沖突,否則插入行時多個主服務器會試圖使用相同的auto_increment值。
服務器變量auto_increment_increment和auto_increment_offset可以幫助協調多主服務器復制和AUTO_INCREMENT列。每個變量有一個默認的(并且是最小的)值1,最大值為65,535。
將這些變量設置為非沖突的值,當在同一個表主插入新行時,多主服務器配置主的服務器將不會與AUTO_INCREMENT值沖突。
這兩個變量這樣影響AUTO_INCREMENT列:
· auto_increment_increment控制列值增加的間隔。例如:
· mysql> SHOW VARIABLES LIKE 'auto_inc%';
· +--------------------------+-------+
· | Variable_name | Value |
· +--------------------------+-------+
· | auto_increment_increment | 1 |
· | auto_increment_offset | 1 |
· +--------------------------+-------+
· 2 rows in set (0.00 sec)
·
· mysql> CREATE TABLE autoinc1 (col INT NOT NULL AUTO_INCREMENT PRIMARY KEY);
· Query OK, 0 rows affected (0.04 sec)
·
· mysql> SET @auto_increment_increment=10;
· Query OK, 0 rows affected (0.00 sec)
·
· mysql> SHOW VARIABLES LIKE 'auto_inc%';
· +--------------------------+-------+
· | Variable_name | Value |
· +--------------------------+-------+
· | auto_increment_increment | 10 |
· | auto_increment_offset | 1 |
· +--------------------------+-------+
· 2 rows in set (0.01 sec)
·
· mysql> INSERT INTO autoinc1 VALUES (NULL), (NULL), (NULL), (NULL);
· Query OK, 4 rows affected (0.00 sec)
· Records: 4 Duplicates: 0 Warnings: 0
·
· mysql> SELECT col FROM autoinc1;
· +-----+
· | col |
· +-----+
· | 1 |
· | 11 |
· | 21 |
· | 31 |
· +-----+
· 4 rows in set (0.00 sec)
(這里注明如何使用SHOW VARIABLES以獲得這些變量的當前值)。
· auto_increment_offset確定AUTO_INCREMENT列值的起點。影響到在復制設置主可以有多少主服務器(例如將該值設置為10表示設置可以支持10個服務器)。
考慮下面的命令,假定在前面所示示例中的相同的會話中執行這些命令:
mysql> SET @auto_increment_offset=5;
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW VARIABLES LIKE 'auto_inc%';
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| auto_increment_increment | 10 |
| auto_increment_offset | 5 |
+--------------------------+-------+
2 rows in set (0.00 sec)
mysql> CREATE TABLE autoinc2 (col INT NOT NULL AUTO_INCREMENT PRIMARY KEY);
Query OK, 0 rows affected (0.06 sec)
mysql> INSERT INTO autoinc2 VALUES (NULL), (NULL), (NULL), (NULL);
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> SELECT col FROM autoinc2;
+-----+
| col |
+-----+
| 5 |
| 15 |
| 25 |
| 35 |
+-----+
4 rows in set (0.02 sec)
詳細信息參見5.3.3節,“服務器系統變量”。