MySQL 中带有自动增量主键的两列?
使用 MyISAM 引擎实现这一点。下面带自动增量的两个列作为主键的示例。
创建一个拥有两个列作为主键的表格 −
mysql> create table TwoPrimaryKeyTableDemo -> ( -> Result ENUM('First','Second','Third','Fail') not null, -> StudentId int not null auto_increment, -> StudentName varchar(200) not null, -> Primary key(Result,StudentId) -> ) -> ENGINE=MyISAM; Query OK, 0 rows affected (0.20 sec)
向表格中插入记录
mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result) values('John','Fail'); Query OK, 1 row affected (0.42 sec) mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result)values('Carol','First'); Query OK, 1 row affected (0.09 sec) mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result) values('Smith','Third'); Query OK, 1 row affected (0.05 sec) mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result) values('Johnson','Second'); Query OK, 1 row affected (0.03 sec) mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result) values('Johnson','Third'); Query OK, 1 row affected (0.06 sec) mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result) values('Carol','Second'); Query OK, 1 row affected (0.18 sec) mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result) values('Carol','Fail'); Query OK, 1 row affected (0.05 sec)
现在我们可以借助带有 order by 子句的选择语句来检查记录。查询如下。
mysql> select *from TwoPrimaryKeyTableDemo order by StudentId,Result;
以下是输出 —
+--------+-----------+-------------+ | Result | StudentId | StudentName | +--------+-----------+-------------+ | First | 1 | Carol | | Second | 1 | Johnson | | Third | 1 | Smith | | Fail | 1 | John | | Second | 2 | Carol | | Third | 2 | Johnson | | Fail | 2 | Carol | +--------+-----------+-------------+ 7 rows in set (0.00 sec)
广告