zoukankan      html  css  js  c++  java
  • 2017-9-18视图,触发器,事物,存储过程,函数

    • 视图
     
    视图是一个虚拟表(非真实存在),其本质是【根据SQL语句获取动态的数据集,并为其命名】,用户使用时只需使用【名称】即可获取结果集,可以将该结果集当做表来使用。
    
    使用视图我们可以把查询过程中的临时表摘出来,用视图去实现,这样以后再想操作该临时表的数据时就无需重写复杂的sql了,直接去视图中查找即可,但视图有明显地效率问题,并且视图是存放在数据库中的,如果我们程序中使用的sql过分依赖数据库中的视图,即强耦合,那就意味着扩展sql极为不便,因此并不推荐使用
    #准备表
    #学生表
    create table student(sid int primary key auto_increment,
                        sname varchar(5),
                        teacher_id int,
                        foreign key (teacher_id) references teacher(tid)
                        on update cascade
        on delete cascade);
    #插入数据
    insert into student(sname,teacher_id) values('刘一',1),('陈二',2),
                                                ('张三',3),('李四',4),
                                                ('王五',1),('赵六',2),
                                                ('孙七',3),('周八',4),
                                                ('吴九',1),('郑十',2);
                                                
    #查看数据
    mysql> select * from student;
    +-----+-------+------------+
    | sid | sname | teacher_id |
    +-----+-------+------------+
    |   1 | 刘一  |          1 |
    |   2 | 陈二  |          2 |
    |   3 | 张三  |          3 |
    |   4 | 李四  |          4 |
    |   5 | 王五  |          1 |
    |   6 | 赵六  |          2 |
    |   7 | 孙七  |          3 |
    |   8 | 周八  |          4 |
    |   9 | 吴九  |          1 |
    |  10 | 郑十  |          2 |
    +-----+-------+------------+
    10 rows in set (0.00 sec)
                                                
                                        
    #教师表   
    create table teacher(tid int primary key auto_increment,
                        tname varchar(10));
    #插入数据
    insert into teacher(tname)values('爱根'),('艾利克斯'),('元灏'),('舞沛气');
    #查看数据
    mysql> select * from teacher;
    +-----+----------+
    | tid | tname    |
    +-----+----------+
    |   1 | 爱根     |
    |   2 | 艾利克斯 |
    |   3 | 元灏     |
    |   4 | 舞沛气   |
    +-----+----------+
    4 rows in set (0.00 sec)
    
    #测试
    #查询属于egon老师的学生
    select sname from student where teacher_id in (select tid from teacher where tname = '爱根'); 
    
    +-------+
    | sname |
    +-------+
    | 刘一  |
    | 王五  |
    | 吴九  |
    +-------+
    3 rows in set (0.00 sec)                                    
    ##############################创建视图##################################
    #语法:create view teacher_view as select tid from teacher where tname = '爱根';
    #于是属于爱根老师的学生的姓名可以改写为
    select sname from student where teacher_id = (select tid from teacher_view);
    #查询结果
    +-------+
    | sname |
    +-------+
    | 刘一  |
    | 王五  |
    | 吴九  |
    +-------+
    3 rows in set (0.00 sec)
    
    #!!!注意注意注意:
    #1. 使用视图以后就无需每次都重写子查询的sql,但是这么效率并不高,还不如我们写子查询的效率高
    
    #2. 而且有一个致命的问题:视图是存放到数据库里的,如果我们程序中的sql过分依赖于数据库中存放的视图,那么意味着,一旦sql需要修改且涉及到视图的部分,则必须去数据库中进行修改,而通常在公司中数据库有专门的DBA负责,你要想完成修改,必须付出大量的沟通成本DBA可能才会帮你完成修改,极其地不方便。
    
    
    ###############################使用视图##################################
    #修改视图,原始表也跟着改
    mysql> select * from student;
    +-----+-------+------------+
    | sid | sname | teacher_id |
    +-----+-------+------------+
    |   1 | 刘一  |          1 |
    |   2 | 陈二  |          2 |
    |   3 | 张三  |          3 |
    |   4 | 李四  |          4 |
    |   5 | 王五  |          1 |
    |   6 | 赵六  |          2 |
    |   7 | 孙七  |          3 |
    |   8 | 周八  |          4 |
    |   9 | 吴九  |          1 |
    |  10 | 郑十  |          2 |
    +-----+-------+------------+
    10 rows in set (0.00 sec)
    
    #创建student的视图
    create view student_view as select * from student;
    Query OK, 0 rows affected (0.04 sec)
    
    mysql> select * from student_view;
    +-----+-------+------------+
    | sid | sname | teacher_id |
    +-----+-------+------------+
    |   1 | 刘一  |          1 |
    |   2 | 陈二  |          2 |
    |   3 | 张三  |          3 |
    |   4 | 李四  |          4 |
    |   5 | 王五  |          1 |
    |   6 | 赵六  |          2 |
    |   7 | 孙七  |          3 |
    |   8 | 周八  |          4 |
    |   9 | 吴九  |          1 |
    |  10 | 郑十  |          2 |
    +-----+-------+------------+
    10 rows in set (0.00 sec)
     #更新视图中的数据
     update course_view set sname = 'xxx';
        Query OK, 10 rows affected (0.04 sec)
        Rows matched: 10  Changed: 10  Warnings: 0
    #往视图中插入数据
    mysql> insert into student_view values(11,'hello',1);
    Query OK, 1 row affected (0.06 sec)
    #发现原始表的记录也跟着修改了
    select * from student;
    mysql> select * from student;
    +-----+-------+------------+
    | sid | sname | teacher_id |
    +-----+-------+------------+
    |   1 | xxx   |          1 |
    |   2 | xxx   |          2 |
    |   3 | xxx   |          3 |
    |   4 | xxx   |          4 |
    |   5 | xxx   |          1 |
    |   6 | xxx   |          2 |
    |   7 | xxx   |          3 |
    |   8 | xxx   |          4 |
    |   9 | xxx   |          1 |
    |  10 | xxx   |          2 |
    |  11 | hello |          1 |
    +-----+-------+------------+
    11 rows in set (0.00 sec)
    
    ###我们不应该修改视图中的记录,而且在涉及多个表的情况下是根本无法修改视图中的记录的,
    
    
    ###############################修改视图##################################
    语法:alter view 视图名称 as sql语句;
    
    mysql> alter view teacher_view as select * from student where sid > 5;
    Query OK, 0 rows affected (0.04 sec)
    
    mysql> select * from  teacher_view;
    +-----+-------+------------+
    | sid | sname | teacher_id |
    +-----+-------+------------+
    |   6 | xxx   |          2 |
    |   7 | xxx   |          3 |
    |   8 | xxx   |          4 |
    |   9 | xxx   |          1 |
    |  10 | xxx   |          2 |
    |  11 | hello |          1 |
    +-----+-------+------------+
    6 rows in set (0.00 sec)
    
    ###############################删除视图##################################
    
    语法:DROP VIEW 视图名称
    
    drop view teacher_view;
    Query OK, 0 rows affected (0.00 sec)
    
    
    • 触发器
    使用触发器可以定制用户对表进行【增、删、改】操作时前后的行为,注意:没有查询
    #创建触发器的语法
    CREATE
        TRIGGER trigger_name
        trigger_time trigger_event
        ON tbl_name FOR EACH ROW
        trigger_body
    
    trigger_time: { BEFORE | AFTER }
    trigger_event: { INSERT | UPDATE | DELETE }
    
    #第一步:准备表
    create table cmd_log_tesk(
    id int primary key auto_increment,
    cmd_name char(64),
    sub_time datetime,
    user_name char(32),
    is_success enum('yes','no')
    );
    
    create table err_log_task(
    id int primary key auto_increment,
    cname char(64),
    stime datetime
    );
    
    #第二步:创建触发器
    delimiter //
    CREATE
        TRIGGER tri_after_insert_cmd_log_tesk
        after insert
        ON cmd_log_tesk FOR EACH ROW
    BEGIN
        if new.is_success = 'no' then
            insert into err_log_task(cname,stime) values(new.cmd_name,new.sub_time);
        end if;
    END //
    delimiter ;
    
    #测试
    insert into cmd_log_tesk(cmd_name,sub_time,user_name,is_success) values
    ('ls -l /etc | grep *.conf',now(),'root','no'), #NEW.id,NEW.cmd_name,NEW.sub_time
    ('ps aux |grep mysqld',now(),'root','yes'),
    ('cat /etc/passwd |grep root',now(),'root','yes'),
    ('netstat -tunalp |grep 3306',now(),'egon','no');
    Query OK, 4 rows affected (0.35 sec)
    Records: 4  Duplicates: 0  Warnings: 0
    查看插入的数据
    mysql> select * from cmd_log_tesk;
    +----+----------------------------+---------------------+-----------+------------+
    | id | cmd_name                   | sub_time            | user_name | is_success |
    +----+----------------------------+---------------------+-----------+------------+
    |  1 | ls -l /etc | grep *.conf   | 2017-09-18 19:02:03 | root      | no         |
    |  2 | ps aux |grep mysqld        | 2017-09-18 19:02:03 | root      | yes        |
    |  3 | cat /etc/passwd |grep root | 2017-09-18 19:02:03 | root      | yes        |
    |  4 | netstat -tunalp |grep 3306 | 2017-09-18 19:02:03 | egon      | no         |
    +----+----------------------------+---------------------+-----------+------------+
    4 rows in set (0.00 sec)
                
    查看错误日志
    mysql> select * from err_log_task;
    +----+----------------------------+---------------------+
    | id | cname                      | stime               |
    +----+----------------------------+---------------------+
    |  1 | ls -l /etc | grep *.conf   | 2017-09-18 19:02:03 |
    |  2 | netstat -tunalp |grep 3306 | 2017-09-18 19:02:03 |
    +----+----------------------------+---------------------+
    2 rows in set (0.00 sec)
    

    #删除触发器
    drop trigger 触发器名

    • 事物
    #事务用于将某些操作的多个SQL作为原子性操作,一旦有某一个出现错误,即可回滚到原来的状态,从而保证数据库数据完整性。
    #测试数据
    create table user(id int primary key auto_increment,
                     name varchar(10),
                     balance int);
    
    insert into user (name, balance) values ('陈阳',1000),
    ('潘斌',1000),('刘武',1000);
    
    
    #原子操作
    start transaction;
    update user set balance = 900 where name = '刘武';#转账100
    update user set balance = 1010 where name = '潘斌';#中间手续费10
    update user set balance = 1090 where name = '陈阳';#收账90
    commit;
    mysql> select * from user;
    +----+------+---------+
    | id | name | balance |
    +----+------+---------+
    |  1 | 陈阳 |    1090 |
    |  2 | 潘斌 |    1010 |
    |  3 | 刘武 |     900 |
    +----+------+---------+
    3 rows in set (0.00 sec)
    
    
    #出现异常,回滚到初始状态
    start transaction;
    update user set balance=900 where name='刘武'; #买支付100元
    update user set balance=1010 where name='潘斌'; #中介拿走10元
    uppdate user set balance=1090 where name='城阳'; #卖家拿到90元,出现异常没有拿到
    rollback;
    commit;
    
    mysql> select  * from user;
    +----+------+---------+
    | id | name | balance |
    +----+------+---------+
    |  1 | 陈阳 |    1090 |
    |  2 | 潘斌 |    1010 |
    |  3 | 刘武 |     900 |
    +----+------+---------+
    3 rows in set (0.00 sec)
    

    • 存储过程

    #存储过程包含了一系列可执行的sql语句,存储过程存放于MySQL中,通过调用它的名字可以执行其内部的一堆sql
    #使用存储过程的优点:
    #1. 用于替代程序写的SQL语句,实现程序与sql解耦
    #2. 基于网络传输,传别名的数据量小,而直接传sql数据量大
    #使用存储过程的缺点:
    #1. 执行效率低
    #2. 程序员扩展功能不方便
    
    #创建测试数据;
    create table task(id int primary key auto_increment,
                     name varchar(10),
                     age int(5));
    
    insert into task(name,age) values('张三',18),
    ('李四',18),
    ('赵武',19),
    ('王六',11);
    
    mysql> select * from task;
    +----+------+------+
    | id | name | age  |
    +----+------+------+
    |  1 | 张三 |   18 |
    |  2 | 李四 |   18 |
    |  3 | 赵武 |   19 |
    |  4 | 王六 |   11 |
    +----+------+------+
    4 rows in set (0.00 sec)
    
    *********************************创建存储过程*****************************
    #1.创建简单存储过程(无参)
    delimiter //
    create procedure h1()
    begin
        select * from task;
        insert into task(name,age) values('xxx',18);
    end //
    delimiter ;
    
    在mysql中调用
    
    call h1();
    mysql> call h1();
    +----+------+------+
    | id | name | age  |
    +----+------+------+
    |  1 | 张三 |   18 |
    |  2 | 李四 |   18 |
    |  3 | 赵武 |   19 |
    |  4 | 王六 |   11 |
    +----+------+------+
    4 rows in set (0.00 sec)
    
    Query OK, 1 row affected (0.05 sec)
    
    
    #在Python中基于pymysql调用
    代码:
    import pymysql
    conn = pymysql.connect(host='localhost',
                           user = 'root',
                           password = '',
                           database = 'day48',
                           charset = 'utf8')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    res = cursor.callproc('h1')
    conn.commit()
    print(cursor.fetchall())
    cursor.close()
    conn.close()
    
    输出结果:
        [{'id': 1, 'name': '张三', 'age': 18},
         {'id': 2, 'name': '李四', 'age': 18}, 
         {'id': 3, 'name': '赵武', 'age': 19}, 
         {'id': 4, 'name': '王六', 'age': 11},
         {'id': 5, 'name': 'xxx', 'age': 18}]
    
    
    
    #2.创建简单存储过程(有参)
    对于存储过程,可以接受参数,其中参数有三类:
    (1)
        .in      仅用于传入参数
        delimiter //
        create procedure h2(
            in n1 int,
            in n2 int 
        )
        begin 
            select * from task where id between n1 and n2;
        end //
        delimiter;
        # 在mysql中调用
        mysql> call h2(1,3);
        +----+------+------+
        | id | name | age  |
        +----+------+------+
        |  1 | 张三 |   18 |
        |  2 | 李四 |   18 |
        |  3 | 赵武 |   19 |
        +----+------+------+
        3 rows in set (0.00 sec)
        Query OK, 0 rows affected (0.00 sec)
    
        #在Python中基于pymysql调用
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        res = cursor.callproc('h2',args = (1,4))
        
    ********************************************************************    
    
    (2)out     仅用于返回值用
    delimiter //
    create procedure h3(
        in n3 int,
        out res1 int
    )
    BEGIN
        select * from task where id > n3;
        set res1 = 1;
    END //
    delimiter ;
    
    #在mysql中调用
    set @res1=0; #0代表假(执行失败),1代表真(执行成功)
    call p3(3,@res1);
    mysql> call h3(3,@res1);
    +----+------+------+
    | id | name | age  |
    +----+------+------+
    |  4 | 王六 |   11 |
    |  5 | xxx  |   18 |
    |  6 | xxx  |   18 |
    +----+------+------+
    3 rows in set (0.00 sec)
    
    Query OK, 0 rows affected (0.01 sec)
    select @res1;
    mysql> select @res1;
    +-------+
    | @res1 |
    +-------+
    |     1 |
    +-------+
    1 row in set (0.00 sec)
    
    
    #在python中基于pymysql调用
    res = cursor.callproc('h3',args = (1,4)) #0相当于set @res=0
    print(cursor.fetchall()) #查询select的查询结果
    执行结果:
    [{'id': 2, 'name': '李四', 'age': 18},
     {'id': 3, 'name': '赵武', 'age': 19}, 
     {'id': 4, 'name': '王六', 'age': 11},
     {'id': 5, 'name': 'xxx', 'age': 18},
     {'id': 6, 'name': 'xxx', 'age': 18}]
    
    cursor.execute('select @_h3_0,@_h3_1;') #@p3_0代表第一个参数,@p3_1代表第二个参数,即返回值
    print(cursor.fetchall())
    执行结果
        [{'@_h3_0': 1, '@_h3_1': 1}]
    
    
    ********************************************************************    
    (3)inout    既可以传入又可以当做返回值
    
    delimiter //
    create procedure h4(
        inout h4 int
    )
    BEGIN
        select * from task where id > h4;
        set h4 = 1;
    END //
    delimiter ;
    
    #在mysql中调用
    mysql> set @x=3;
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> call h4(@x);
    +----+------+------+
    | id | name | age  |
    +----+------+------+
    |  4 | 王六 |   11 |
    |  5 | xxx  |   18 |
    |  6 | xxx  |   18 |
    +----+------+------+
    3 rows in set (0.00 sec)
    
    Query OK, 0 rows affected (0.01 sec)
    
    mysql> select @x;
    +------+
    | @x   |
    +------+
    |    1 |
    +------+
    1 row in set (0.00 sec)
    
    #在python中基于pymysql调用
    cursor.callproc('h4',(3,))
    print(cursor.fetchall()) #查询select的查询结果
    执行结果:
    [{'id': 3, 'name': '赵武', 'age': 19}, 
     {'id': 4, 'name': '王六', 'age': 11},
     {'id': 5, 'name': 'xxx', 'age': 18},
     {'id': 6, 'name': 'xxx', 'age': 18}]
    
    
    cursor.execute('select @_p4_0;') 
    print(cursor.fetchall())
    
    执行结果
    [{'@_h4_0': 1}]
    
    ###############################执行存储过程##################################
    #在mysql中执行存储过程
    -- 无参数
    call proc_name()
    
    -- 有参数,全in
    call proc_name(1,2)
    
    -- 有参数,有in,out,inout
    set @t1=0;
    set @t2=3;
    call proc_name(1,2,@t1,@t2)
    
    #在Python基于pymysql执行存储过程
    import pymysql
    conn = pymysql.connect(host='localhost',
                           user = 'root',
                           password = '',
                           database = 'day48',
                           charset = 'utf8')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    # res = cursor.callproc('h2',args = (1,4))#基于有参的
    # res = cursor.callproc('h')#基于无参数的
    res = cursor.callproc('h4',args = (2,))#基于inout
    res1 = cursor.execute('select @_h4_0;')
    
    conn.commit()
    print(cursor.fetchall())
    cursor.close()
    conn.close()
    
    ###############################删除存储过程##################################
    drop procedure 存储过程名

    • 函数
    CHAR_LENGTH(str)
            返回值为字符串str 的长度,长度的单位为字符。一个多字节字符算作一个单字符。
            对于一个包含五个二字节字符集, LENGTH()返回值为 10, 而CHAR_LENGTH()的返回值为5。
    
        CONCAT(str1,str2,...)
            字符串拼接
            如有任何一个参数为NULL ,则返回值为 NULL。
        CONCAT_WS(separator,str1,str2,...)
            字符串拼接(自定义连接符)
            CONCAT_WS()不会忽略任何空字符串。 (然而会忽略所有的 NULL)。
    
        CONV(N,from_base,to_base)
            进制转换
            例如:
                SELECT CONV('a',16,2); 表示将 a 由16进制转换为2进制字符串表示
    
        FORMAT(X,D)
            将数字X 的格式写为'#,###,###.##',以四舍五入的方式保留小数点后 D 位, 并将结果以字符串的形式返回。若  D 为 0, 则返回结果不带有小数点,或不含小数部分。
            例如:
                SELECT FORMAT(12332.1,4); 结果为: '12,332.1000'
        INSERT(str,pos,len,newstr)
            在str的指定位置插入字符串
                pos:要替换位置其实位置
                len:替换的长度
                newstr:新字符串
            特别的:
                如果pos超过原字符串长度,则返回原字符串
                如果len超过原字符串长度,则由新字符串完全替换
        INSTR(str,substr)
            返回字符串 str 中子字符串的第一个出现位置。
    
        LEFT(str,len)
            返回字符串str 从开始的len位置的子序列字符。
    
        LOWER(str)
            变小写
    
        UPPER(str)
            变大写
    
        LTRIM(str)
            返回字符串 str ,其引导空格字符被删除。
        RTRIM(str)
            返回字符串 str ,结尾空格字符被删去。
        SUBSTRING(str,pos,len)
            获取字符串子序列
    
        LOCATE(substr,str,pos)
            获取子序列索引位置
    
        REPEAT(str,count)
            返回一个由重复的字符串str 组成的字符串,字符串str的数目等于count 。
            若 count <= 0,则返回一个空字符串。
            若str 或 count 为 NULL,则返回 NULL 。
        REPLACE(str,from_str,to_str)
            返回字符串str 以及所有被字符串to_str替代的字符串from_str 。
        REVERSE(str)
            返回字符串 str ,顺序和字符顺序相反。
        RIGHT(str,len)
            从字符串str 开始,返回从后边开始len个字符组成的子序列
    
        SPACE(N)
            返回一个由N空格组成的字符串。
    
        SUBSTRING(str,pos) , SUBSTRING(str FROM pos) SUBSTRING(str,pos,len) , SUBSTRING(str FROM pos FOR len)
            不带有len 参数的格式从字符串str返回一个子字符串,起始于位置 pos。带有len参数的格式从字符串str返回一个长度同len字符相同的子字符串,起始于位置 pos。 使用 FROM的格式为标准 SQL 语法。也可能对pos使用一个负值。假若这样,则子字符串的位置起始于字符串结尾的pos 字符,而不是字符串的开头位置。在以下格式的函数中可以对pos 使用一个负值。
    
            mysql> SELECT SUBSTRING('Quadratically',5);
                -> 'ratically'
    
            mysql> SELECT SUBSTRING('foobarbar' FROM 4);
                -> 'barbar'
    
            mysql> SELECT SUBSTRING('Quadratically',5,6);
                -> 'ratica'
    
            mysql> SELECT SUBSTRING('Sakila', -3);
                -> 'ila'
    
            mysql> SELECT SUBSTRING('Sakila', -5, 3);
                -> 'aki'
    
            mysql> SELECT SUBSTRING('Sakila' FROM -4 FOR 2);
                -> 'ki'
    
        TRIM([{BOTH | LEADING | TRAILING} [remstr] FROM] str) TRIM(remstr FROM] str)
            返回字符串 str , 其中所有remstr 前缀和/或后缀都已被删除。若分类符BOTH、LEADIN或TRAILING中没有一个是给定的,则假设为BOTH 。 remstr 为可选项,在未指定情况下,可删除空格。
    
            mysql> SELECT TRIM('  bar   ');
                    -> 'bar'
    
            mysql> SELECT TRIM(LEADING 'x' FROM 'xxxbarxxx');
                    -> 'barxxx'
    
            mysql> SELECT TRIM(BOTH 'x' FROM 'xxxbarxxx');
                    -> 'bar'
    
            mysql> SELECT TRIM(TRAILING 'xyz' FROM 'barxxyz');
                    -> 'barx'
    
    部分内置函数

    #1 基本使用
    ************************************************************************************
    mysql> SELECT DATE_FORMAT('2009-10-04 22:23:00', '%W %M %Y');
    +------------------------------------------------+
    | DATE_FORMAT('2009-10-04 22:23:00', '%W %M %Y') |
    +------------------------------------------------+
    | Sunday October 2009                            |
    +------------------------------------------------+
    1 row in set (0.02 sec)
    ************************************************************************************
    mysql> SELECT DATE_FORMAT('2007-10-04 22:23:00', '%H:%i:%s');
    +------------------------------------------------+
    | DATE_FORMAT('2007-10-04 22:23:00', '%H:%i:%s') |
    +------------------------------------------------+
    | 22:23:00                                       |
    +------------------------------------------------+
    1 row in set (0.00 sec)
    
    ************************************************************************************
    mysql> SELECT DATE_FORMAT('1900-10-04 22:23:00','%D %y %a %d %m %b %j');
    +-----------------------------------------------------------+
    | DATE_FORMAT('1900-10-04 22:23:00','%D %y %a %d %m %b %j') |
    +-----------------------------------------------------------+
    | 4th 00 Thu 04 10 Oct 277                                  |
    +-----------------------------------------------------------+
    1 row in set (0.00 sec)
    ************************************************************************************
    mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00','%H %k %I %r %T %S %w');
    +-----------------------------------------------------------+
    | DATE_FORMAT('1997-10-04 22:23:00','%H %k %I %r %T %S %w') |
    +-----------------------------------------------------------+
    | 22 22 10 10:23:00 PM 22:23:00 00 6                        |
    +-----------------------------------------------------------+
    1 row in set (0.00 sec)
    ************************************************************************************
    mysql> SELECT DATE_FORMAT('1999-01-01', '%X %V');
    +------------------------------------+
    | DATE_FORMAT('1999-01-01', '%X %V') |
    +------------------------------------+
    | 1998 52                            |
    +------------------------------------+
    1 row in set (0.00 sec)
    ************************************************************************************
    mysql> SELECT DATE_FORMAT('2006-06-00', '%d');
    +---------------------------------+
    | DATE_FORMAT('2006-06-00', '%d') |
    +---------------------------------+
    | 00                              |
    +---------------------------------+
    1 row in set (0.00 sec)
    ************************************************************************************
    
    
    #2 准备表和记录
    CREATE TABLE blog (
        id INT PRIMARY KEY auto_increment,
        NAME CHAR (32),
        sub_time datetime
    );
    
    INSERT INTO blog (NAME, sub_time)
    VALUES
        ('第1篇','2015-03-01 11:31:21'),
        ('第2篇','2015-03-11 16:31:21'),
        ('第3篇','2016-07-01 10:21:31'),
        ('第4篇','2016-07-22 09:23:21'),
        ('第5篇','2016-07-23 10:11:11'),
        ('第6篇','2016-07-25 11:21:31'),
        ('第7篇','2017-03-01 15:33:21'),
        ('第8篇','2017-03-01 17:32:21'),
        ('第9篇','2017-03-01 18:31:21');
    
    #3. 提取sub_time字段的值,按照格式后的结果即"年月"来分组
    SELECT DATE_FORMAT(sub_time,'%Y-%m'),COUNT(1) FROM blog GROUP BY DATE_FORMAT(sub_time,'%Y-%m');
    
    #结果
    +-------------------------------+----------+
    | DATE_FORMAT(sub_time,'%Y-%m') | COUNT(1) |
    +-------------------------------+----------+
    | 2015-03                       |        2 |
    | 2016-07                       |        4 |
    | 2017-03                       |        3 |
    +-------------------------------+----------+
    rows in set (0.00 sec)
    
    需要掌握函数:date_format













  • 相关阅读:
    限制页面只能在框架页中
    Excel导入的HDR=YES; IMEX=1详解
    ASP复制文件
    C#获取当前日期时间
    SQL语句添加删除修改字段
    C#代码调用页面javascript函数
    JavaScript 层
    vue-router实现SPA购物APP基本功能
    iOS自定义从底部弹上来的View
    RabbitMQ消息队列生产者和消费者
  • 原文地址:https://www.cnblogs.com/De-Luffy/p/7544832.html
Copyright © 2011-2022 走看看