MySQL学习笔记六

一、case when

        case when的用为:从原有数据新增出新的数据

        利用旧数据,形成新的数据进行输出(如:形成新的分类进行输出)

需求:根据成绩分等级,成绩<60的为C等,成绩在[60,80]为B等,成绩>80为A等

        这里的等级用case来设置输出,case when ... then... when...then...else...end

select sid,(case 
            when score<60 then 'C'
            when score>=60 and score<=80 then 'B'
            else 'A'
            end) as level
from sc;

        上面是用case when来根据成绩输出等级,那么如何一步到位对等级进行计数呢,可以利用sum/count + case when,每一个等级利用一次case when及聚合函数,三个等级利用三次

需求:根据成绩划分等级并根据等级计数

        记得每个case要有一个end做结尾

select sum(case when score<60 then 1 else 0 end) as C,
       sum(case when score>=60 and score<=80 then 1 else 0 end) as B
       count(case when score>80 then 1 else null end) as A
from sc;

二、保存结果表-as/like

        数据的持久化:as是直接复制,like是复制表结构

1.as-直接复制

        create table tablename as ...    这里...是一个表结果输出,不能是一个表

drop table if exists `re1`;
create table re1 as
    select sum(case when score<60 then 1 else 0 end) as C,
       sum(case when score>=60 and score<=80 then 1 else 0 end) as B
       count(case when score>80 then 1 else null end) as A
    from sc;

drop table if exists `sc2`;
create table sc2 as 
    select * from sc;

2.like-复制表结构

        create table tablename like  tablename    这里tablename是一个实体表,不能是一个结果

drop table if exists commodity;
create table commoditytype like ishop1.commoditytype;

三、触发器

        监控表,当被监控的表的数据发生变化时自动执行某SQL语句,此时用到了触发器。

        触发器的应用场景:①每当增加一个顾客到某个数据表时,需要检查他的电话号码格式是否正确;②每当增加一个订单时,从库存中减去相应的数量;③无论何时删除一行,都在某个数据表中保留一个副本。

        即上述的例子都是需要在某个表发生更改时自动处理。

        delete、insert、update语句支持触发器,自动执行一条SQL语句,其他语句不支持触发器。

        创建触发器要素:唯一的触发器名称、触发器关联的表(被监控的表)、触发器响应的活动(insert、delete、updateÿ

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值