#表中主鍵的定義: mysql> create table t12 ( -> id int primary key, -> name char(2) -> ); #表中插入數據: mysql> create table t13 ( id int, name char(2), primary key(id) ); Query OK, 0 rows affected (0.01 sec) 查看兩張表的表結構. mysql> desc t12; +-------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+---------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | name | char(2) | YES | | NULL | | +-------+---------+------+-----+---------+-------+ 2 rows in set (0.00 sec) mysql> desc t13 -> ; +-------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+---------+------+-----+---------+-------+ | id | int(11) | NO | PRI | 0 | | | name | char(2) | YES | | NULL | | +-------+---------+------+-----+---------+-------+ 2 rows in set (0.00 sec) #注意primary key是惟一不容許重複的. mysql> insert into t12 values (3,"aa"); Query OK, 1 row affected (0.01 sec) mysql> insert into t12 values (3,"bb"); ERROR 1062 (23000): Duplicate entry '3' for key 'PRIMARY' 主鍵的自增(aotu_increment): mysql> create table t14 ( id int auto_increment, name char(4) ); ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key 報錯提示:表中只能有1個自增加的key. auto_increment列只能有1列爲auto_increment,且此列必須加索引(index/key). mysql> create table t14 ( id int auto_increment, name char(4),key id(id) ); Query OK, 0 rows affected (0.02 sec) 在t14表中name列插入兩條數據,查看primary key(id)是否自增. mysql> insert into t14 (name) values ("lisi"); Query OK, 1 row affected (0.00 sec) mysql> insert into t14 (name) values ("zhan"); Query OK, 1 row affected (0.00 sec) mysql> select * from t14; +----+------+ | id | name | +----+------+ | 1 | lisi | | 2 | zhan | +----+------+ 2 rows in set (0.00 sec) 最多見的主鍵的自增建表寫法. mysql> create table t15 ( -> id int primary key auto_increment, -> name char(10) -> ); Query OK, 0 rows affected (0.01 sec)