1.DDL基础扩展
1.alter
1.更改表名:alter table 表名 rename 新表名;
2.更改字段名,类型:alter table 表名 change 列名 新列名 数据类型;
3.添加字段:alter table 表名 add 列名 类型;
4.删除字段:alter table 表名 drop 列名;
5.更改字段类型(尽量不要更改):alter table 表名 modify 列名 新数据类型;
6.修改数据库字符集:alter database 数据库名 character set utf8;
注:需要重启MySQL服务才能生效
7.修改表字符集:alter table 表名 character set utf8 collate utf8_general_ci;
2.DDL增强
1.约束
约束类型: 主键 外键 唯一 非空 自增 默认值
关键字: primary key foreign key unique not null auto_increment default
主键设置:
第一种:创建表语句时添加主键约束
create table person(
id int,
primary key(id) //id int primary key,
)
第二种:创建后通过alter添加
alter table person add primary key(id);
主键自增:(可以自增的只有一列,且是主键中的一个)
第一种:建表时
create table person(
id int auto_increment,
primary key(id)
)
第二种:建表后
alter table person modify id int auto_increment;
设置自增起始值:
alter table 表名 auto_increment=值;
关联完整性(外键):
外键列的值,必须是关联表中的已有主键值,也可以为空
第一种:建表时
create table student(
id int,
foreign key(外键列 列名) references 主键列(列名)
);
第二种:建表后
alter table 表名 add foreign key(外键列列名) references 指向的表名(主键列列名);
唯一约束 unique
唯一约束是指定table的列或列组合不能重复,保证数据的唯一性。
唯一约束不允许出现重复的值,但是可以为多个null.
第一种:建表时
create table temp(
id int,
unique(id) //id int unique
)
第二种:建表后
alter table temp add unique(id);
非空约束 not null 与 默认值 default
所有的类型的值都可以是null,包括int、float 等数据类型,设置为not null的字段,必须填入数据
经常和default一起使用,当不填写数据的时候,把默认值设置成指定的值
第一种:建表时
create table temp(
id int not null
)
第二种:建表后
alter table temp modify id int not null;
条件判断:
and:合并表达式
select 列限定 from 表限定 where A表达式 and B表达式;
or:
select 列限定 from 表限定 where A表达式 or B表达式;
注意 : 如果 一个语句中,同时出现了and和or的话,and优先级高
关系表达式:
=:相等 <>:不等
判断是否为空 is null / 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 开始值(不包含) ,条数;
3.单表查询(组函数):
分组关键字使用 group by
count(*) : 总条数
max(字段名) : 最大值
min(字段名) : 最小值
avg(字段名) : 平均值
sum(字段名) : 总和
select count(*),max(字段名),min(字段名)... from 表名 group by 字段名; //根据字段名分组
having:过滤
select teacher_id, avg(score) as avg from student group by teacher_id having avg > 60;
***先分组,再过滤,让where后面可以使用列限定的值
4.union 与 union all
Union 会去除重复项
Union all 不会去除重复项
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个参数代表截取字符个数