SQL基础

2020-06-10  本文已影响0人  吵吵人

学习网站:https://www.w3school.com.cn/sql/index.asp
推荐工具书:SQL必知必会

基本认识

基本操作

insert into 表名不加引号 (字段名不加引号1,字段名不加引号2,……字段名不加引号n)
values ('对应的数值1', '对应的数值2', ……'对应的数值n')
;
select 字段名1 as A, 字段名2
from  表名
where 筛选字段 in ('筛选字段内容1','筛选字段内容2')
order by 排序字段 desc
;

as将字段名1重新命名为A,order表示排序,后面加desc表示倒序排序

# 不分组
select
count(字段) as 字段计数
,count(distinct 字段) as 计数去重
from 表名
;
# 分组
select 分组字段
,count(distinct 字段)
,sum(字段)
from 表名
where 表筛选条件
and 表筛选条件
group by 分组字段

分组实际上就是分类统计,比如说不分组统计的是所有部门的所有员工人数, 按部门分组之后就是统计各个部门的员工人数。

其他地方又说:WHERE 关键字无法与聚合函数一起使用??

select 表别名.字段
from 表 a
join 表b
on 两表的关联条件(如a.字段=b.字段)
and 表b的筛选条件
where 表a的筛选条件

例:

select a.工号,a.姓名,a.部门,b.综合考核分
from
(
select 工号,姓名
from 表A名
where 部门 in ('市场部','客服部')
) a
inner join
(
select 工号,综合考核分
from 表B名
where 综合考核分>=80
) b
on a.工号=b.工号

这样,就能查询到'市场部'和'客服部'综合考核分>=80的员工了~
上述可以改写成

select a.工号,a.姓名,a.部门,b.综合考核分
from 表A名 a
join 表B名 b
on a.工号=b.工号
and b.综合考核分>=80
where a.部门 in ('市场部','客服部')

建议新手用第一种写法,第二种的写法更简单

注意:join 默认的就是内联结inner join ,只有都满足条件的记录才会保留下来。此外还有
left out join:主表(表a)记录全部保留,从表(表b)若无记录则相应字段为null
right out join:从表全部保留
full join:两个表全部保留

要注意表可能有重复的记录,避免出错

select date_add(数据创建时间,interval 12 month)
,姓名
,工号
from 表名
where 数据创建时间>'2019-15-05 12:01:01'

条件函数

case when <判断表达式> then <表达式> else<表达式> end

如:

select a.工号, a.姓名,b.工号,b.综合考核分
,case when 综合考核分>=90 then '优秀'
when 综合考核分<90 then '良好'
end as level
from 表A名 a
left outer join 表B名 b
on a.工号=b.工号

查询排名前三:

select * from personinfo order by credit DESC limit 0,3

limit 0,3:从0开始,提取三条

上一篇下一篇

猜你喜欢

热点阅读