1 DDL基础拓展
Alter:
更改表名
alter table 表名 rename 新表名;
更改字段名,类型
alter table 表名 change 列名 新列名 数据类型;
添加字段
alter table 表名 add 列名 类型;
删除字段
alter table 表名 drop 列名;
更改字段类型(轻易不改)
alter table 表名 modify 列名 新数据类型;
修改数据库字符集
alter database 数据库名 character set utf8 需要重启mysql服务才能生效
修改表字符集
alter table 表名 character set utf8 collate utf8_general_ci
2 DDL增强
2.1 约束
主键约束
1)创建表语句时,添加主键约束
primary key(id)
2)创建表完成以后,通过alter添加主键约束
alter table 表名 add primary key(列名)
主键自增
1)建表时,添加自增
create table 表名(
列名1 类型 auto_increment,
列名2 类型,
primary key(列名1)
);
2)创建表之后添加自增
alter table 表名 modify 主键列名 类型 auto_increment;
设置自增的起始值
alter table 表名 auto_increment=值;
关联完整性(外键)
1)创建表时添加外键约束
foreign key(外键列列名) references 表名(主键列列名)
2)创建完表时,添加外键约束
alter table 表名 add foreign key(外键列列名) references 指向的表名(主键列列名);
唯一约束 unique
1)创建表时,添加unique约束
列名 类型 unique;
2)创建表之后,添加unique约束
alter table 表名 add unique(列名)
not null 和 default 常一起用
1)创建表时,添加约束
列名 类型 not null 设置为not null的字段,必须填数据
列名 类型 default 默认值 设置为default的字段,不填写数据时,默认值为指定值
2)创建表之后,添加约束
alter table 表名 modify 列名 数据类型 not null default 默认值;
2.2 条件判断
and
select 列限定 from 表限定 where A表达式 and B表达式;
or
select 列限定 from 表限定 where A表达式 or B表达式;
注意 : 如果 一个语句中,同时出现了and和or的话,and优先级高
关系表达式
判断为空查询学生中,成绩为空的学生不能使用 = null ,应该使用 is null
select * from student where score is null;
select * from student where score is not null;
between...and...
在...之间
select 列限定 from 表限定 where 列名 between 值1 and 值2;
in
在指定数据中
select 列限定 from 表限定 where 列名 in(值1,值2....);
模糊查询 like
其中 % 匹配任意个数的任意字符
_ 匹配单个任意字符
select 列限定 from 表限定 where 列名 like '值' ;
order by 排序
select 列限定 from 表限定 order by 列名 asc/desc;
Asc : 升序
Desc : 降序
limit
限制条数,通常和order by一起使用,因为我们使用排序之后,再去获取前几条数据,比较有价值,比如成绩前三名
select 列限定 from 表限定 limit 条数;
select 列限定 from 表限定 limit 开始值(不包含),条数;
2.3 单表查询(组函数)
count(*) max(字段名) min(字段名) avg(字段名) sum(字段名)
起别名 : 表名 as '名字'
group by
select teacher_id, count(*) from student group by teacher_id;
having
select teacher_id, avg(score) as avg from student where avg > 60 group by teacher_id;
这种情况时,进行where语句时avg还没有意义,所以要用having过滤,having放在group by后面
select teacher_id, avg(score) as avg from student group by teacher_id having avg > 60;
2.4 union与union all
合并查询,合并查询的结果
Union 会去除重复项
Union all 不会去除重复项
使用union和union all时要放在两条select语句中间,且前一句不加分号
尽量使用union all,把去重这个工作交给代码去完成,这样可以减少MYSQL服务器的压力
使用union / union all的时候要注意:
1)参与合并的表,它们SELECT出来的字段数量必须一致(强制规则)
2)参与合并的表,它们SELECT出来的字段的类型建议一一对应(非强制,但是最好遵循这条规则)
3)参与合并的表,它们SELECT出来的字段的顺序建议一致(非强制,但是最好遵循这条规则)
2.5 常用函数
select version() ;显示当前MySQL软件的版本
select database();显示当前所处数据库是哪个
select char_length('中国');返回字符个数。
select length('中国');返回字符所占字节数,MySQL中,一个UTF8编码的汉字占3个字节
select concat( 'a', 'b', 'c', 'd');返回 'abcd'。字符串拼接函数
select concat_ws( '=', 'a', 'b', 'c');返回 'a=b=c'。字符串拼接函数,第一个是拼接间隔符
select upper('abcd');返回ABCD。将参数中所有小写字母转换为大写
select lower('ABCD');返回abcd。将参数中所有大写字母转换为小写
select substring( '系统信息类', 1, 3 );返回 系统信。第2个参数代表从1开始的第几个字符,第3个参数代表截取字符个数