MYSQL-约束,条件判断,组函数
主键约束
1.创建表时候定义约束
create table person(
id int ,
name varchar(100),
income decimal(18,2),
primary key (id,name)
);
2.创建表之后,使用alter添加主键
alter table person3 add primary key(id);
主键自增
1.创建表的时候定义
create table person4(
id int auto_increment ,
name varchar(200),
primary key(id)
);
2.创建表之后,使用alter定义自增
alter table person5 modify id int auto_increment;
//设置自增起始值
alter table person6 auto_increment=10000;
外键约束
1.创建表时添加外键约束
create table teacher(
id int ,
name varchar(20),
primary key (id)
);
create table student (
id int ,
name varchar(20),
teacher_id int ,
primary key (id),
foreign key (teacher_id) references teacher(id)
);
2.创建完表之后,添加外键约束
alter table student1 add foreign key (teacher_id) references teacher1 (id);
唯一约束
1.创建表时,添加unique约束
create table temp (
id int ,
`name` varchar(20),
unique(id)
);
或
create table temp (
id int unique ,
`name` varchar(20)
);
2.创建表之后,添加unique约束
alter table temp1 add unique (id);
非空约束,默认约束
1. 创建表时,添加约束
create table temp2(
id int not null,
`name` varchar(30) default 'abc',
sex varchar(10) not null default '男'
);
2. 创建表时,添加约束
alter table temp3 modify id int not null ;
alter table temp3 modify name varchar(30) default 'abc';
alter table temp3 modify sex varchar(10) not null default '男';
条件判断
1.and
select * from student where name='张三' and score > 90;
2.or
select * from student where name='张三' or score > 90;
关系表达式
- > , >= , < , <= ,<>,=
- > : 大于
- < : 小于
- >= : 大于等于
- <= : 小于等于
- = : 相等
- <> : 不等于
3.between and
select 列限定 from 表限定 where 列名 between 值1 and 值2;
4.in
select 列限定 from 表限定 where 列名 in(值1,值2....);
5.模糊查询 like
select 列限定 from 表限定 where 列名 like '值' ;
- 其中 % 匹配任意个数的任意字符
- _ 匹配单个任意字符
6.order by 排序
select 列限定 from 表限定 order by 列名 asc/desc;
Asc : 升序
Desc : 降序
7.limit
select 列限定 from 表限定 limit 条数;
select 列限定 from 表限定 limit 开始值(不包含) ,条数;
组函数
- count(*) : 总条数
- max(字段名) : 最大值
- min(字段名) : 最小值
- avg(字段名) : 平均值
- sum(字段名) : 总和
1.group by
select teacher_id, count(*) as stu_count from student group by teacher_id;
2.Having
select teacher_id, avg(score) as avg from student group by teacher_id having avg > 60;
子查询
1.Union与 union all
- 合并查询,合并查询的结果
- Union 会去除重复项
- Union all 不会去除重复项
select * from student where teacher_id=1
union
select * from student where score > 60;
select * from student where teacher_id=1
union all
select * from student where score > 60;
它俩的作用是把两张表或者更多表合并成一张表
2.常用函数
- 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个参数代表截取字符个数