数据准备
drop table if exists class;
create table class(
class_no int(2) unsigned zerofill primary key auto_increment comment ‘班级编号‘,
class_name varchar(30) not null comment ‘班级名称‘
);
insert into class values(1, ‘培优班‘);
insert into class values(2, ‘普通班‘);
drop table if exists student;
create table student(
stu_no int(2) unsigned zerofill primary key auto_increment comment ‘学员编号‘,
stu_name varchar(30) not null comment ‘学员姓名‘,
stu_sex varchar(3) not null comment ‘学员性别‘,
stu_age tinyint(2) unsigned zerofill comment ‘学员年代‘,
class_no int(2) unsigned zerofill comment ‘所在班级编号‘,
foreign key(class_no) references class(class_no)
);
insert into student values(01, ‘李白‘, ‘男‘, 18, 01);
insert into student values(02, ‘杜甫‘, ‘男‘, 20, 01);
insert into student values(03, ‘张飞‘, ‘男‘, 32, 02);
insert into student values(04, ‘韩信‘, ‘男‘, 26, 02);
insert into student values(05, ‘了龙‘, ‘男‘, 27, 02);
insert into student values(06, ‘大乔‘, ‘女‘, 17, 01);
insert into student values(07, ‘小乔‘, ‘女‘, 16, 01);
insert into student values(08, ‘小乔‘, ‘女‘, 16, 01);
insert into student values(09, ‘关哥‘, ‘男‘, 32, 02);
insert into student values(10, ‘刘备‘, ‘男‘, 36, null);
alter table student drop foreign key `student_ibfk_1`;
1: [ order by ] 排序
例: select * from student;
例: select * from student order by stu_age; --对学生年龄进行排序
例: select * from student order by stu_age desc; --desc表示的就是从大到小排序,默认是升序
例: select * from student order by stu_age asc; --asc表示从小到排序,默认的就是asc
例: select * from student order by stu_age asc, stu_no desc; --如果一个字段不能区分大小时,则可以按照第二个字段来区分
字符集与校对规则
例: show character set; --查看mysql数据库所支持的字符集
例: show collation;
例: show collation like ‘gbk%‘;
ps: 每个字符集都会提供一个或者多个校对规则, 一般的校对规则命名是: 字符集_地域名_ci|cs|bin;
ci: 表示不区分大小写;
cs: 表示区分大小写;
bin: 表示使用编码比较; [a-z]:[97-122] [A-Z]:[65-90]
create table t_1(
name varchar(20)
) character set gbk collate gbk_chinese_ci;
insert into t_1 values(‘C‘),(‘a‘),(‘B‘);
select * from t_1 order by name;
create table t_2(
name varchar(20)
) character set gbk collate gbk_bin;
insert into t_2 values(‘C‘),(‘a‘),(‘B‘);
select * from t_2 order by name;
*******************************************************************************************************
2: [ limit ]限制获得的记录数
语法: limit offset, row count。 offset表示索引值(从0开始), row count表示要获取的记录数
select * from student;
例: select * from student limit 1, 5; --从第二条数据开始获取,获取5条数据
例: select * from student limit 1, 50; --如果要获取的数据,超过了总共的记录数,这时则会获取所有的
例: select * from student limit 5; --如果只有一个参数时同则表示要获取的记录数,从0开始获取
*******************************************************************************************************
3: [ distinct ] 除去重复的记录
ps: 只有要查询的字段值全部完全相同时,才能算是重复,并不是部分的字段相同
例: select distinct stu_name from student;
例: select distinct stu_name, stu_age from student;
例: select distinct stu_no, stu_name, stu_age from student; --这里不能去重,因为没有重复的记录
例: select all stu_name, stu_age from student; --all与distinct相反, all表示获取到所有的记录, 但默认就是all