一:字段修饰符 (约束)
1:null和not null修饰符
我们通过举例说明这两个修饰符的作用
mysql> create table worker(id int not null,name varchar(8) not null,pass varchar(20) not null);
插入数据试试
mysql> insert into worker values(1,‘aa’,null);
ERROR 1048 (23000): Column ‘pass’ cannot be null
mysql> create table wdsj(id int,name varchar(10),pass int);
mysql> desc wdsj;
±------±------------±-----±----±--------±------+
| Field | Type | Null | Key | Default | Extra |
±------±------------±-----±----±--------±------+
| id | int | YES | | NULL | |
| name | varchar(10) | YES | | NULL | |
| pass | int | YES | | NULL | |
±------±------------±-----±----±--------±------+
插入null会发现报错,所以not null,意思就是不能为空;但是可以为空值,空值同样也是一个值。
默认字段是null,也就是允许为空。
空值是不占用空间的;mysql中的NULL其实是占用空间的
NULL 其实并不是空值,而是要占用空间,所以mysql在进行比较的时候,NULL 会参与字段比较,所以对效率有一部分影响;而且索引时不会存储NULL值的,所以如果索引的字段可以为NULL,索引的效率会下降很多。
select * from table where column <> ‘’ 查询字段为空值的字段
select * from table where column is not null 查询字段不为空的字段
2:default 设定字段的默认值
mysql>create table test2(name varchar(8) not null,dept varchar(25) default ‘SOS’);
mysql> insert into test(name) values(‘wdsj’);
mysql> insert into test values(‘aa’, ‘ss’);
mysql> select * from test;
±-----±-----+
| name | dept |
±-----±-----+
| wdsj | SOS |
| aa | ss |
±-----±-----+
可以看出来,配置了default字段,默认是SOS,只要不插入其他值,默认都是该值。
3:auto_increment字段约束
自动增长
只能修饰 int字段。 表明mysql应该自动为该字段生成一个唯一没有用过的数(每次在最大ID值的基础上加1。特例:如果目前最大ID是34,然后删除34,新添加的会是35.)。对于主键,这是非常 有用的。 可以为每条记录创建一个惟一的标识符
mysql> create table wdsj(id int not null auto_increment primary key,label varchar(20) not null);
mysql> insert into wdsj(label) values(‘aa’);
mysql> insert into wdsj(label) values(‘bb’);
mysql> insert into wdsj values(4, ‘cc’);
mysql> insert into wdsj(label) values(‘dd’);
mysql> select * from wdsj;
±—±------+
| id | label |
±—±------+
| 1 | aa |
| 2 | bb |
| 4 | cc |
| 5 | dd |
可以看出来,自动增长字段,由1开始增加,但是自己插入了数字4之后,自动增长会以4开始
删除表中所有记录,清auto_increment 值。
truncate table name;
二:索引
索引是一种特殊的文件(InnoDB数据表上的索引是表空间的一个组成部分),它们包含着对数据表里所有记录的引用指针。更通俗的说,数据库索引好比是一本书前面的目录,能加快数据库的查询速度。
优点:为了加快搜索速度,减少查询时间 。
缺点:
索引是以文件存储的。如果索引过多,占磁盘空间较大。而且他影响: insert ,update ,delete 执行时间。
索引中数据必须与数据表数据同步:如果索引过多,当表中数据更新的时候后,索引也要同步更新,这就降低了效率。
索引的类型
1、普通索引
2、唯一性索引
3、主键索引(主索引)
4、复合索引
1:普通索引
如果觉得《MySQL第二课:约束 索引 外键 视图》对你有帮助,请点赞、收藏,并留下你的观点哦!