简单查询

查询一个字段

1
select 字段名 from 表名;

注意:select和from都是关键字,字段名和表名都是标识符

查询多个字段

使用逗号隔开

1
select 字段名1,字段名2 from 表名;

查询所有字段

1
select * from 表名;

注意:这种查询效率低、可读性差

给查询的列起别名

1
select 字段名 as 新字段名 from 表名;

使用as关键字起别名,但是原列表名不会改变
如果别名中有空格,则把别名写成 ‘别名’
字段可以用数学表达式

去除重复记录

distinct关键字

1
select distinct 字段名 from 表名;

注意:distinct只能出现在字段的最前面

条件查询

条件查询不是将表中所有数据都查出来,是查询出来符合条件的

1
select 字段1,字段2,字段3 from 表名 where 条件;

条件

=(等于)

1
select 字段 from 表名 where 字段=xxx;

!=或<>(不等于)

1
select 字段 from 表名 where 字段!=xxx;

<(小于)[大于同理]

1
select 字段 from 表名 where 字段<xxx;

between….and….(两个值之间)

等同于>= and <=

1
select 字段 from 表名 where 字段 between xxx and xxx;

is null 为 null (is not null (不为空))

1
select 字段 from 表名 where 字段 is null;

注意:在数据库中null不能以等号衡量,需要用is,因为null不是一个值。

and(并且)[or同理]

1
select 字段 from 表名 where 字段=xxx and 字段=xxxx;

注意:and和or同时出现时,and优先级比or高

in(包含)

相当于多个or(not in(不在这个范围内))
in(字段,字段)

1
select 字段 from 表名 where in(字段,字段);

注意:in不是区间,是具体的值

like(模糊查询)

支持%或下划线匹配,%匹配任意个字符,下划线是一个下划线只匹配一个字符
例如:找出名字里含有o的

1
select 字段 from 表名 where 字段 like '%o%';

如果是以o开始的则写成 ‘o%’
如果是以o结尾的则写成 ‘%o’
如果是第二个字母是o的则写成 ‘_o%’,以此类推
如果查找的字段里有下划线则在下划线前面加个 转义字符\

排序

一个字段的排序

1
select 字段名 from 表名 order by 字段;(默认升序)
1
select 字段名 from 表名 order by 字段 desc;(指定降序)
1
select 字段名 from 表名 order by 字段 asc;(指定升序)

多个字段排序

1
select 字段名 from 表名 order by 字段 asc,字段 asc;

函数

数据处理函数

数据处理函数又被称为单行处理函数
单行处理函数特点:一个输入对应一个输出

常见的单行处理函数

lower(转换小写)

1
select lower(字段) from 表名;

upper(转换大写)

1
select upper(字段) from 表名;

substr

取子串,被截取的字符串,起始下标,截取的长度

1
select substr(字段,起始下标,起始下标) from 表名;

concat(进行字符串的拼接)

1
select concat(字段,字段) from 表名;

length(取长度)

1
select length(字段) from 表名;

trim(去空格)

1
select trim(字段) from 表名;

str_to_date(将字符串转换成日期)

点击查看

date_format(格式化日期)

点击查看

round(四舍五入)

1
select round(小数,1(保留一位小数)) from 表名;

注意:如果是-1则保留到十位,依次类推。

rand()(生成随机数)

1
select rand() from 表名;

ifnull(可以将null转换成一个具体值)

1
select ifnull(数据,被当成的值) from 表名;

case..when..then..when..then..else..end

案例:当员工的工作岗位是MANAGER的时候,工资上调10%,当工作岗位是SALESMAN的时候,工资上调50%,其他正常。

1
2
3
4
5
6
7
select 
ename,job,
(case job when 'MANAGER' then sal*1.1 when 'SALESMAN' then sal*1.5 else sal end)
as
newsal
from
emp;

分组函数

分组函数又称为多行处理函数
多行处理函数特点:多个输入对应一个输出
常见的多行处理函数

count(计数)

1
select count(字段) from 表名;

sum(求和)

1
select sum(字段) from 表名;

avg(平均值)

1
select avg(字段) from 表名;

max(最大值)

1
select max(字段) from 表名;

min(最小值)

1
select min(字段) from 表名;

注意:
1.分组函数在使用的时候必须先进行分组,然后才能使用。如果没有对数据进行分组,整张表默认为一组。
2.分组函数自动忽略null。
3.分组函数中count()和count(字段)的区别
count(
):统计表当中的总行数。(只要有一行数据,count++)
count(字段):表示统计该字段下所有不为null的元素的总数。
4.分组函数不能直接使用在where子句中。(因为分组函数在使用的时候必须先分组)
5.所有的分组函数可以组合起来用。

分组查询

分组查询:在实际的应用中,可能有这样的需求,需要先分组,然后对每一组数据进行操作。这个时候我们需要使用分组查询

group up

1
2
3
4
5
6
select
...
from
...
group by
...

注意:在一条select语句中,如果有group by语句的话,select后面只能跟参加分组的字段,以及分组函数,其他一律不能跟。

having(对分完组的数据进一步过滤)

having不能单独使用,having不能代替where,having必须和group by联合使用。
注意:where和having,优先使用where,where使用不了的才用having。