Mysql 的自然序并“无序”
1.问题
mysql 的执行结果中,是否是按照主键有序排列的?
2.实战
2.1创建带有主键,唯一索引表
- 创建表
animals
mysql> create table animals(id int primary key,name varchar(30),unique key(name))engine = innodb;
Query OK, 0 rows affected (0.20 sec)
- 插入数据
mysql> insert into animals values
-> (1,'Tiger'),
-> (2,'Dog'),
-> (3,'cat');
Query OK, 3 rows affected (0.03 sec)
Records: 3 Duplicates: 0 Warnings: 0
- 选择数据
mysql> select * from animals;
+----+-------+
| id | name |
+----+-------+
| 3 | cat |
| 2 | Dog |
| 1 | Tiger |
+----+-------+
3 rows in set (0.00 sec)
从选择的结果集中可以看出,这里的结果集是跟主键没有关系的(倒是和这个唯一索引有些关系)
2.1创建仅有主键表
- 创建
student
表create table student(id int primary key,name varchar(20));
- 插入数据
insert into student values
(1,'Hadoop'),
(2,'spark'),
(3,'java'),
(4,'scala');
- 执行选择
mysql> select * from student;
+----+--------+
| id | name |
+----+--------+
| 1 | Hadoop |
| 2 | spark |
| 3 | java |
| 4 | scala |
+----+--------+
4 rows in set (0.00 sec)
- 如果在name上添加一个唯一索引?
mysql> alter table student add unique index uid_name(name);^C
- 再次选择
mysql> select * from student;
+----+--------+
| id | name |
+----+--------+
| 1 | Hadoop |
| 3 | java |
| 4 | scala |
| 2 | spark |
+----+--------+
4 rows in set (0.00 sec)