InnoDB表都是有主鍵的,如果沒有顯示定義主鍵,則InnoDB首先判斷表中是否有非空的唯一索引,如果有,該列即為主鍵。如果有多個單一列唯一索引,則按照唯一索引順序,排在前的為主鍵。
mysql> show create table t2\G
Create Table: CREATE TABLE
t2
( a
int(11) DEFAULT NULL, b
int(11) NOT NULL, c
int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
在表t2上添加多個唯一索引,不按照列的順序添加。
mysql> alter table t2 add unique (a),add unique (c),add unique (b);
Query OK, 0 rows affected (0.09 sec)
Records: 0 Duplicates: 0 Warnings: 0
t2
a
b
c
UNIQUE KEY c
c
), b
b
a
a
)
現在唯一索引的順序是a,c,b,從建表語句就已經可以看出順序了,現在唯一索引的順序變成了c,b,a,插入資料。
mysql> insert into t2 (b,c) values (1,2);
Query OK, 1 row affected (0.01 sec)
mysql> insert into t2 (b,c) values (10,20);
Query OK, 1 row affected (0.00 sec)
mysql> insert into t2 (a,b,c) values (10,20,30);
mysql> select a,b,c,_rowid from t2;
| a | b | c | _rowid |
+------+----+----+--------+
| NULL | 1 | 2 | 2 |
| NULL | 10 | 20 | 20 |
| 10 | 20 | 30 | 30 |
+------+----+----+--------+
3 rows in set (0.00 sec)
**_rowid列是InnoDB存儲引擎自動建立的一個6位元組大小的指針,此時可看出_rowid是以c列為主鍵,因選擇主鍵的條件是非空的唯一索引,之後才按照唯一索引的順序來選擇主鍵。
如果表中無顯示主鍵,也沒有非空的唯一索引,那麼主鍵是如何定義的呢?**
mysql> create table t3(a int,b int,c int);
Query OK, 0 rows affected (0.06 sec)
mysql> insert into t3 select 1,2,3;
Records: 1 Duplicates: 0 Warnings: 0
mysql> insert into t3 select 2,3,4;
mysql> insert into t3 select 3,4,5
建立表t3,并插入資料,且資料沒有null值,但是列a,b,c都是可為null的列
mysql> select a,b,c,_rowid from t3\G
ERROR 1054 (42S22): Unknown column '_rowid' in 'field list'
此時表中沒有自動生成_rowid列。下面更改b列為not null
mysql> alter table t3 modify b int(11) not null;
Query OK, 0 rows affected (0.10 sec)
mysql> show create table t3\G
t3
a
b
c
int(11) DEFAULT NULL
更改列為not null依然沒有自動生成_rowid列。再次為c列添加可為空的唯一索引
mysql> alter table t3 add unique (c);
t3
a
b
c
c
c
**也就是說如果表中沒有顯示指定主鍵,非空且唯一索引是必須條件。
如果表中有一個多列唯一索引,情況又将如何呢?**
mysql> alter table t3 modify c int(11) not null;
Query OK, 0 rows affected, 1 warning (0.11 sec)
Records: 0 Duplicates: 0 Warnings: 1
mysql> alter table t3 add unique (b,c);
t3
a
b
c
b
b
,
c
**總結:
從我這裡的實驗可以看出,如果沒有顯示定義主鍵,單一列非空的唯一索引即為主鍵。**