1、不论是建表,添加新列时,都需要使用common进行注释。
2、所有的列必须设置为非空(not null),默认值可以设置为"",datetime类型的数据默认值设置为current_timestamp。
3、表的主键一般设置为BIGINT,自增属性auto_increment,步长为二,用来进行分库的数据备份。
4、varchar()属性括号里指的是字符数。
5、设置id自动增长的步长与初始值的语句
set @@auto_increment_increment=2;步长
set @@auto_increment_offset=1;初始值
这两个语句是全局有效的,步长没有表内设置,表初始值可以用auto_increment=3来设置。
需要注意的是如果全局初始值设置为奇数,就算表初始值设置为偶数也是无效的,新添加的数据项的id会是该偶数加一,之后再依次加二。
6、创建表时要使用engine = InnoDB来指明需要使用的数据库引擎。
7、查看表的自增属性使用show variables like '%auto%';
8、创建表时添加索引使用index idx_name(列名);
额外新建索引使用create index 索引名 on表名(列名);或alter table 表名add index 索引名(列名)。
以下为例子:
set @@auto_increment_increment=2;
set @@auto_increment_offset=1;
drop table if exists `user`;
create table `user`
(
id Bigint primary key AUTO_INCREMENT comment'用户id',
name varchar(20) not null default '' comment '用户名',
password varchar(20) not null default '' comment '用户密码',
createAt datetime not null default current_timestamp comment '改组数据的创建时间',
updateAt datetime not null default current_timestamp comment '该组数据的最后更新时间'
)
engine = InnoDB
comment 'user表,用来保存用户信息'
auto_increment=1;
查询语句:
select u.name'name',count(createuserid)'开设的课程数'
from `user` as u
left join lesson as l on u.id=l.createuserid
group by u.name
order by '开设的课程数' desc;
在它前面使用explain命令查看查询的复杂度。