> ### ***MySQL语言***
* [ ] DDL 数据定义语言,create,drop,alter
* [ ] DML 数据操作语言,insert,update,delete
* [ ] DQL 数据查询语言, select
* [ ] DCL 数据控制语言, grant,commit,rollback
*****
```
select distinct username from user; 查询出唯一值
select username from user is null; 查询空值null
select username from user is not null; 查询非空值
```
*****
> ### ***like使用方法***
* [ ] “%” 匹配所有
* [ ] “\_” 匹配一个字符
> ### ***regexp正则查询***
```
select * from tablename where name regexp "^php"; 查询以php开头
select * from tablename where name regexp "php$"; 查询以php结尾
```
> ### *** MySQL常用函数***
```
concat():连接函数
rand():随机数
count():统计个数
sum():求和
avg():平均值
max():最大值
min():最小值
select * from tablename order by rand() limit 3; 随机查出3条数据
```
> ### ***group by分组聚合***
```
select concat(class_id,'-','class') as class,count(id) as total from user group by class_id; #查询各班级的总人数
```
> ### *** 多表查询***
```
select * from user where id in (select max(id) from user); #嵌套查询
```
一对一
一对多 多个的留另外一个id
一个表一个主体
两个表是一对一关系,则可以合并
*****
> ### ***链接查询***
```
select * from class,user left join user on class.id = user.class\_id;
select class.name,count(user.id) from class left join user on class.id = user.class\_id group by class.id;
```
```
#所有班的总人数统计出来,将没有人数的班级也要统计出来
select class.name, if(count(user.id),count(user.id),'无') from class left join user on class.id = user.class\_id group by class.id;
#所有班的总人数统计出来,将没有人数的班级也要统计出来,将人数为0的显示出无
```
> 内链接inner join on,完全等于普通多表查询,必须是符合条件的多个表的数据才会显示!
> 右链接:把右边的表数据全部输出
> 左链接:把左边的表数据全部输出
*****
求出及格与不及格的人数,一条sql写出:
第一种方案:(简单)
```
select (select count(*) from user where score>=60) as '及格', (select count(\*) from user where score<60) as '不及格'
```
第二种方案:
```
select sum(if(scroe>=60),1,0)) '及格', sum(if(scroe<60),1,0)) '不及格' from user;
having
```
要在分组聚合后用having,此时where不能用
```
select class_id from user group by class_id having class_id<2;
```