mysql续集6

1.权限管理

    1、创建账号
        # 本地账号
        create user 'egon1'@'localhost' identified by '123'; # mysql -uegon1 -p123
        # 远程帐号
        create user 'egon2'@'192.168.31.10' identified by '123'; # mysql -uegon2 -p123 -h 服务端ip
        create user 'egon3'@'192.168.31.%' identified by '123'; # mysql -uegon3 -p123 -h 服务端ip
        create user 'egon3'@'%' identified by '123'; # mysql -uegon3 -p123 -h 服务端ip

    2、授权
        user:*.*
        db:db1.*
        tables_priv:db1.t1
        columns_priv:id,name

        grant all on *.* to 'egon1'@'localhost';
        grant select on *.* to 'egon1'@'localhost';
        revoke select on *.* from 'egon1'@'localhost';

        grant select on db1.* to 'egon1'@'localhost';
        revoke select on db1.* from 'egon1'@'localhost';

        grant select on db1.t2 to 'egon1'@'localhost';
        revoke select on db1.t2 from 'egon1'@'localhost';

        grant select(id,name),update(age) on db1.t2 to 'egon1'@'localhost';

2.pymysql模块

2.1pymysql使用

1.首先安装模块
pip install pymysql

2.准备数据
mysql> show create table userinfo\G;
*************************** 1. row ***************************
       Table: userinfo
Create Table: CREATE TABLE `userinfo` (
  `id` int(11) NOT NULL,
  `name` varchar(10) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

ERROR: 
No query specified

mysql> 

mysql> select * from userinfo;
+----+------+----------+
| id | name | password |
+----+------+----------+
|  1 | vita | 123      |
|  2 | lili | 123      |
+----+------+----------+
2 rows in set (0.00 sec)

mysql> 
3.pymysql连接数据库
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import pymysql
user=input('用户名: ').strip()
pwd=input('密码: ').strip()

#链接
conn=pymysql.connect(host='10.0.0.61',
                     user='root',
                     password='123',
                     database='db1',
                     charset='utf8')
#游标
#cursor=conn.cursor() #执行完毕返回的结果集默认以元组显示
cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)
#执行sql语句
sql='select * from userinfo where name="%s" and password="%s"' %(user,pwd) #注意%s需要加引号
print(sql)
res=cursor.execute(sql) #执行sql语句,返回sql查询成功的记录数目
print(res)

cursor.close()
conn.close()

if res:
    print('登录成功')
else:
    print('登录失败')

mysql续集6

2.2execute()之sql注入

1.在sql语句中,--会注释掉后面的语句
2.sql注入之:用户存在,绕过密码
3.sql注入之:用户不存在,绕过了用户与密码

mysql续集6
mysql续集6

解决方法
# 原来是我们对sql进行字符串拼接
# sql="select * from userinfo where name='%s' and password='%s'" %(user,pwd)
# print(sql)
# res=cursor.execute(sql)

#改写为(execute帮我们做字符串拼接,我们无需且一定不能再为%s加引号了)
sql="select * from userinfo where name=%s and password=%s"
#!!!注意%s需要去掉引号,因为pymysql会自动为我们加上
res=cursor.execute(sql,[user,pwd]) 
#pymysql模块自动帮我们解决sql注入的问题,只要我们按照pymysql的规矩来。

2.3pymysql增删改

import pymysql
#链接
conn=pymysql.connect(host='localhost',user='root',password='123',database='egon')
#游标
cursor=conn.cursor()

#执行sql语句
#part1
# sql='insert into userinfo(name,password) values("root","123456");'
# res=cursor.execute(sql) #执行sql语句,返回sql影响成功的行数
# print(res)

#part2-插入一条语句
# sql='insert into userinfo(name,password) values(%s,%s);'
# res=cursor.execute(sql,("root","123456")) #执行sql语句,返回sql影响成功的行数
# print(res)

#part3-插入多条数据
sql='insert into userinfo(name,password) values(%s,%s);'
res=cursor.executemany(sql,[("root","123456"),("lhf","12356"),("eee","156")]) #执行sql语句,返回sql影响成功的行数
print(res)

conn.commit() #提交后才发现表中插入记录成功
cursor.close()
conn.close()

2.4pymysql-查(fetchone,fetchmany,fetchall)

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import pymysql
#链接
conn=pymysql.connect(host='10.0.0.61',
                     user='root',
                     password='123',
                     database='db1',
                     charset='utf8')
#游标
cursor=conn.cursor() #执行完毕返回的结果集默认以元组显示(1, 'vita', '123')
#cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)#{'id': 1, 'name': 'vita', 'password': '123'}
#执行sql语句
sql='select * from userinfo'

rows=cursor.execute(sql)

res1=cursor.fetchone()
cursor.scroll(2,mode='absolute') # 相对绝对位置移动,从头开始移动两个,所以下面从id=3开始
#cursor.scroll(2,mode='relative') # 相对当前位置移动
res2=cursor.fetchmany(2)
res3=cursor.fetchall()
print(res1)
print(res2)
print(res3)

mysql续集6

2.5获取插入的最后一条数据的自增ID

mysql> show create table userinfo\G;
*************************** 1. row ***************************
       Table: userinfo
Create Table: CREATE TABLE `userinfo` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(10) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

ERROR: 
No query specified

mysql> 

mysql> insert into userinfo values('vita2','123'),('lili2','123'),('vita','123');

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import pymysql
#链接
conn=pymysql.connect(host='10.0.0.61',
                     user='root',
                     password='123',
                     database='db1',
                     charset='utf8')
#游标
cursor=conn.cursor()
#执行sql语句
sql='insert into userinfo(name,password) values("xxx","123");'
rows=cursor.execute(sql)
print(cursor.lastrowid)
conn.commit()
cursor.close()
conn.close()

mysql续集6

mysql> select * from userinfo;
+----+-------+----------+
| id | name  | password |
+----+-------+----------+
|  1 | vita2 | 123      |
|  2 | lili2 | 123      |
|  3 | vita  | 123      |
|  4 | xxx   | 123      |
+----+-------+----------+
4 rows in set (0.00 sec)

mysql> 

3.sql内置功能

3.1视图

1.视图是一个虚拟表,本质是根据sql语句获取动态的数据集
2.之后就不需要写过长的sql语句,直接像使用表一样使用视图即可
3.从单个表中查询的数据创建的视图可以修改数据
4.从多个表中查询出的数据创建的视图只能用于查询
5.视图并不推荐使用,因为业务变化频繁,功能总在变如果表修改了,还要找到相应的视图进行修改。

3.2创建视图

mysql> create view user_view as select id,name from userinfo where name like 'vita%';
Query OK, 0 rows affected (0.01 sec)

mysql> select * from user_view;
+----+-------+
| id | name  |
+----+-------+
|  1 | vita2 |
|  3 | vita  |
+----+-------+
2 rows in set (0.01 sec)

mysql> select * from userinfo where id in(select id from user_view);
+----+-------+----------+
| id | name  | password |
+----+-------+----------+
|  1 | vita2 | 123      |
|  3 | vita  | 123      |
+----+-------+----------+
2 rows in set (0.00 sec)

mysql> 

3.3修改视图

"实际使用中,不应该修改视图,而且涉及多个表时,是无法修改视图中的记录的"
mysql> update user_view set name='new_vita' where id=1;#更改视图中的数据
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> insert into user_view values(6,'add_vita');#往视图中插入数据
Query OK, 1 row affected (0.01 sec)

mysql> select * from user_view;#视图中被更改的数据和新加的数据都没有
+----+------+
| id | name |
+----+------+
|  3 | vita |
+----+------+
1 row in set (0.00 sec)

mysql> select * from userinfo;#修改的数据和新加的数据插入到了原表中
+----+----------+----------+
| id | name     | password |
+----+----------+----------+
|  1 | new_vita | 123      |
|  2 | lili2    | 123      |
|  3 | vita     | 123      |
|  4 | xxx      | 123      |
|  6 | add_vita | NULL     |
+----+----------+----------+
5 rows in set (0.00 sec)

mysql> 

mysql> alter view user_view as select * from userinfo ;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from user_view;
+----+----------+----------+
| id | name     | password |
+----+----------+----------+
|  1 | new_vita | 123      |
|  2 | lili2    | 123      |
|  3 | vita     | 123      |
|  4 | xxx      | 123      |
|  6 | add_vita | NULL     |
+----+----------+----------+
5 rows in set (0.00 sec)

mysql> 

3.4删除视图

mysql> drop view user_view;
Query OK, 0 rows affected (0.00 sec)

mysql> 

4.触发器

触发器可以为  [增删改查]  操作的前后增加一些数据操作行为
不推荐使用触发器,对于数据 [增删改查]操作前后,可以从代码层面进行控制,更加灵活。
触发器无法由用户直接调用,而是对表的增删改查操作被动引发的。

4.1创建触发器

# 插入前
CREATE TRIGGER tri_before_insert_tb1 BEFORE INSERT ON tb1 FOR EACH ROW
BEGIN
    ...
END

# 插入后
CREATE TRIGGER tri_after_insert_tb1 AFTER INSERT ON tb1 FOR EACH ROW
BEGIN
    ...
END

# 删除前
CREATE TRIGGER tri_before_delete_tb1 BEFORE DELETE ON tb1 FOR EACH ROW
BEGIN
    ...
END

# 删除后
CREATE TRIGGER tri_after_delete_tb1 AFTER DELETE ON tb1 FOR EACH ROW
BEGIN
    ...
END

# 更新前
CREATE TRIGGER tri_before_update_tb1 BEFORE UPDATE ON tb1 FOR EACH ROW
BEGIN
    ...
END

# 更新后
CREATE TRIGGER tri_after_update_tb1 AFTER UPDATE ON tb1 FOR EACH ROW
BEGIN
    ...
END
#准备表
CREATE TABLE cmd (
    id INT PRIMARY KEY auto_increment,
    USER CHAR (32),
    priv CHAR (10),
    cmd CHAR (64),
    sub_time datetime, #提交时间
    success enum ('yes', 'no') #0代表执行失败
);

CREATE TABLE errlog (
    id INT PRIMARY KEY auto_increment,
    err_cmd CHAR (64),
    err_time datetime
);

"NEW表示即将插入的数据行,OLD表示即将删除的数据行。"
#创建触发器
delimiter //
CREATE TRIGGER tri_after_insert_cmd AFTER INSERT ON cmd FOR EACH ROW
BEGIN
    IF NEW.success = 'no' THEN #等值判断只有一个等号
            INSERT INTO errlog(err_cmd, err_time) VALUES(NEW.cmd, NEW.sub_time) ; #必须加分号
      END IF ; #必须加分号
END//
delimiter ;

#往表cmd中插入记录,触发触发器,根据IF的条件决定是否插入错误日志
INSERT INTO cmd (
    USER,
    priv,
    cmd,
    sub_time,
    success
)
VALUES
    ('egon','0755','ls -l /etc',NOW(),'yes'),
    ('egon','0755','cat /etc/passwd',NOW(),'no'),
    ('egon','0755','useradd xxx',NOW(),'no'),
    ('egon','0755','ps aux',NOW(),'yes');

#查询错误日志,发现有两条
mysql> select * from errlog;
+----+-----------------+---------------------+
| id | err_cmd         | err_time            |
+----+-----------------+---------------------+
|  1 | cat /etc/passwd | 2017-09-14 22:18:48 |
|  2 | useradd xxx     | 2017-09-14 22:18:48 |
+----+-----------------+---------------------+
rows in set (0.00 sec)

插入后触发触发器

4.2删除触发器

drop trigger tri_after_insert_cmd;

5.存储过程

5.1存储过程介绍

存储过程包含了一系列可执行的sql语句,存储过程存放在mysql中,通过名字调用存储过程。
"使用存储过程的优点:"
1.可替代程序写的sql语句,实现了程序与sql语句的解耦。
2.基于网络传输,传输别名的数据量小,传输sql语句的数据量大。
"使用存储过程的缺点:"
1.扩展功能不便。

5.2创建无参存储过程

delimiter //
create procedure p1()
BEGIN
    select * from blog;
    INSERT into blog(name,sub_time) values("xxx",now());
END //
delimiter ;

"mysql中调用p1存储过程"
mysql> call p1();
+----+----------+----------+
| id | name     | password |
+----+----------+----------+
|  1 | new_vita | 123      |
|  2 | lili2    | 123      |
|  3 | vita     | 123      |
|  4 | xxx      | 123      |
|  6 | add_vita | NULL     |
+----+----------+----------+
5 rows in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> 

"python中调用p1存储过程"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import pymysql
#链接
conn=pymysql.connect(host='10.0.0.61',
                     user='root',
                     password='123',
                     database='db1',
                     charset='utf8')
#游标
cursor=conn.cursor()
cursor.callproc('p1')
print(cursor.fetchall())

mysql续集6

5.3创建有参存储过程

对于存储过程,可以接收参数,其参数有三类:

#in          仅用于传入参数用
#out        仅用于返回值用
#inout     既可以传入又可以当作返回值

delimiter //
create procedure p2(
    in n1 int,
    in n2 int
)
BEGIN

    select * from userinfo where id between n1 and n2;
END //
delimiter ;

"mysql调用p2存储过程"
mysql> call p2(2,3);
+----+-------+----------+
| id | name  | password |
+----+-------+----------+
|  2 | lili2 | 123      |
|  3 | vita  | 123      |
+----+-------+----------+
2 rows in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> 

"python中调用p2存储过程"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import pymysql
#链接
conn=pymysql.connect(host='10.0.0.61',
                     user='root',
                     password='123',
                     database='db1',
                     charset='utf8')
#游标
cursor=conn.cursor()
cursor.callproc('p2',(2,3))
print(cursor.fetchall())

mysql续集6

delimiter //
create procedure p3(
    in n1 int,
    out res int
)
BEGIN

    select * from userinfo where id > n1;
    set res=1;
END //
delimiter ;

"MySQL中调用存储过程"
mysql> set @res=0;#0代表假(执行失败),1代表真(执行成功)
Query OK, 0 rows affected (0.00 sec)

mysql> call p3(2,@res);
+----+----------+----------+
| id | name     | password |
+----+----------+----------+
|  3 | vita     | 123      |
|  4 | xxx      | 123      |
|  6 | add_vita | NULL     |
+----+----------+----------+
3 rows in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> select @res;
+------+
| @res |
+------+
|    1 |
+------+
1 row in set (0.00 sec)

mysql> 

"python中调用存储过程"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import pymysql
#链接
conn=pymysql.connect(host='10.0.0.61',
                     user='root',
                     password='123',
                     database='db1',
                     charset='utf8')
#游标
cursor=conn.cursor()
cursor.callproc('p3',(2,0))
print(cursor.fetchall())
cursor.execute('select @_p3_0,@_p3_1;') #@p3_0代表第一个参数,@p3_1代表第二个参数,即返回值
print(cursor.fetchall())

mysql续集6

delimiter //
create procedure p4(
    inout n1 int
)
BEGIN
    select * from userinfo where id > n1;
    set n1 = 1;
END //
delimiter ;

"mysql调用"
mysql> set @x=2;
Query OK, 0 rows affected (0.00 sec)

mysql> call p4(@x);
+----+----------+----------+
| id | name     | password |
+----+----------+----------+
|  3 | vita     | 123      |
|  4 | xxx      | 123      |
|  6 | add_vita | NULL     |
+----+----------+----------+
3 rows in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> select @x;
+------+
| @x   |
+------+
|    1 |
+------+
1 row in set (0.00 sec)

mysql> 

"python中调用"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import pymysql
#链接
conn=pymysql.connect(host='10.0.0.61',
                     user='root',
                     password='123',
                     database='db1',
                     charset='utf8')
#游标
cursor=conn.cursor()
cursor.callproc('p4',(2,))
print(cursor.fetchall())
cursor.execute('select @_p4_0;')
print(cursor.fetchall())

mysql续集6

5.4删除存储过程

drop procedure proc_name;

5.5流程控制

delimiter //
CREATE PROCEDURE proc_if ()
BEGIN

    declare i int default 0;
    if i = 1 THEN
        SELECT 1;
    ELSEIF i = 2 THEN
        SELECT 2;
    ELSE
        SELECT 7;
    END IF;

END //
delimiter ;

if条件语句

5.6循环语句

"while循环"
delimiter //
CREATE PROCEDURE proc_while ()
BEGIN

    DECLARE num INT ;
    SET num = 0 ;
    WHILE num < 10 DO
        SELECT
            num ;
        SET num = num + 1 ;
    END WHILE ;

END //
delimiter ;
" repeat循环"
delimiter //
CREATE PROCEDURE proc_repeat ()
BEGIN

    DECLARE i INT ;
    SET i = 0 ;
    repeat
        select i;
        set i = i + 1;
        until i >= 5
    end repeat;

END //
delimiter ;
"loop"
BEGIN

    declare i int default 0;
    loop_label: loop

        set i=i+1;
        if i<8 then
            iterate loop_label;
        end if;
        if i>=10 then
            leave loop_label;
        end if;
        select i;
    end loop loop_label;

END

6.事务

事务有原子性,一致性,隔离性,持久性
其中原子性:一旦有错误,就回滚到最初样子。

create table user(
id int primary key auto_increment,
name char(32),
balance int
);

insert into user(name,balance)
values
('wsb',1000),
('egon',1000),
('ysb',1000);

#原子操作
start transaction;
update user set balance=900 where name='wsb'; #买支付100元
update user set balance=1010 where name='egon'; #中介拿走10元
update user set balance=1090 where name='ysb'; #卖家拿到90元
commit;

#出现异常,回滚到初始状态
start transaction;
update user set balance=900 where name='wsb'; #买支付100元
update user set balance=1010 where name='egon'; #中介拿走10元
uppdate user set balance=1090 where name='ysb'; #卖家拿到90元,出现异常没有拿到
rollback;
commit;
mysql> select * from user;
+----+------+---------+
| id | name | balance |
+----+------+---------+
|  1 | wsb  |    1000 |
|  2 | egon |    1000 |
|  3 | ysb  |    1000 |
+----+------+---------+
rows in set (0.00 sec)
#介绍
delimiter //
            create procedure p4(
                out status int
            )
            BEGIN
                1. 声明如果出现异常则执行{
                    set status = 1;
                    rollback;
                }

                开始事务
                    -- 由秦兵账户减去100
                    -- 方少伟账户加90
                    -- 张根账户加10
                    commit;
                结束

                set status = 2;

            END //
            delimiter ;

#实现
delimiter //
create PROCEDURE p5(
    OUT p_return_code tinyint
)
BEGIN 
    DECLARE exit handler for sqlexception 
    BEGIN 
        -- ERROR 
        set p_return_code = 1; 
        rollback; 
    END; 

    DECLARE exit handler for sqlwarning 
    BEGIN 
        -- WARNING 
        set p_return_code = 2; 
        rollback; 
    END; 

    START TRANSACTION; 
        DELETE from tb1; #执行失败
        insert into blog(name,sub_time) values('yyy',now());
    COMMIT; 

    -- SUCCESS 
    set p_return_code = 0; #0代表执行成功

END //
delimiter ;

#在mysql中调用存储过程
mysql> set @res=111;
Query OK, 0 rows affected (0.00 sec)

mysql> call p5(@res);
Query OK, 0 rows affected (0.00 sec)

mysql> select @res;
+------+
| @res |
+------+
|    1 |
+------+
1 row in set (0.00 sec)

###################################

"在python中基于pymysql调用存储过程"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import pymysql
#链接
conn=pymysql.connect(host='10.0.0.61',
                     user='root',
                     password='123',
                     database='db1',
                     charset='utf8')
#游标
cursor=conn.cursor()
cursor.callproc('p5',(2,))
print(cursor.fetchall())
cursor.execute('select @_p5_0;')
print(cursor.fetchall())

mysql续集6

7.函数

7.1DATE_FORMAT函数

mysql> SELECT DATE_FORMAT('2009-10-04 22:23:00', '%W %M %Y');
        -> 'Sunday October 2009'
mysql> SELECT DATE_FORMAT('2007-10-04 22:23:00', '%H:%i:%s');
        -> '22:23:00'
mysql> SELECT DATE_FORMAT('1900-10-04 22:23:00',
    ->                 '%D %y %a %d %m %b %j');
        -> '4th 00 Thu 04 10 Oct 277'
mysql> SELECT 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'
mysql> SELECT DATE_FORMAT('1999-01-01', '%X %V');
        -> '1998 52'
mysql> SELECT DATE_FORMAT('2006-06-00', '%d');
        -> '00'

#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)

7.2其他函数

一、数学函数
    ROUND(x,y)
        返回参数x的四舍五入的有y位小数的值

    RAND()
        返回0到1内的随机值,可以通过提供一个参数(种子)使RAND()随机数生成器生成一个指定的值。

二、聚合函数(常用于GROUP BY从句的SELECT查询中)
    AVG(col)返回指定列的平均值
    COUNT(col)返回指定列中非NULL值的个数
    MIN(col)返回指定列的最小值
    MAX(col)返回指定列的最大值
    SUM(col)返回指定列的所有值之和
    GROUP_CONCAT(col) 返回由属于一组的列值连接组合而成的结果    

三、字符串函数

    CHAR_LENGTH(str)
        返回值为字符串str 的长度,长度的单位为字符。一个多字节字符算作一个单字符。
    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)
        变大写

    REVERSE(str)
        返回字符串 str ,顺序和字符顺序相反。

    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'

四、日期和时间函数
    CURDATE()或CURRENT_DATE() 返回当前的日期
    CURTIME()或CURRENT_TIME() 返回当前的时间
    DAYOFWEEK(date)   返回date所代表的一星期中的第几天(1~7)
    DAYOFMONTH(date)  返回date是一个月的第几天(1~31)
    DAYOFYEAR(date)   返回date是一年的第几天(1~366)
    DAYNAME(date)   返回date的星期名,如:SELECT DAYNAME(CURRENT_DATE);
    FROM_UNIXTIME(ts,fmt)  根据指定的fmt格式,格式化UNIX时间戳ts
    HOUR(time)   返回time的小时值(0~23)
    MINUTE(time)   返回time的分钟值(0~59)
    MONTH(date)   返回date的月份值(1~12)
    MONTHNAME(date)   返回date的月份名,如:SELECT MONTHNAME(CURRENT_DATE);
    NOW()    返回当前的日期和时间
    QUARTER(date)   返回date在一年中的季度(1~4),如SELECT QUARTER(CURRENT_DATE);
    WEEK(date)   返回日期date为一年中第几周(0~53)
    YEAR(date)   返回日期date的年份(1000~9999)

    重点:
    DATE_FORMAT(date,format) 根据format字符串格式化date值

       mysql> SELECT DATE_FORMAT('2009-10-04 22:23:00', '%W %M %Y');
        -> 'Sunday October 2009'
       mysql> SELECT DATE_FORMAT('2007-10-04 22:23:00', '%H:%i:%s');
        -> '22:23:00'
       mysql> SELECT DATE_FORMAT('1900-10-04 22:23:00',
        ->                 '%D %y %a %d %m %b %j');
        -> '4th 00 Thu 04 10 Oct 277'
       mysql> SELECT 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'
       mysql> SELECT DATE_FORMAT('1999-01-01', '%X %V');
        -> '1998 52'
       mysql> SELECT DATE_FORMAT('2006-06-00', '%d');
        -> '00'

五、加密函数
    MD5()    
        计算字符串str的MD5校验和
    PASSWORD(str)   
        返回字符串str的加密版本,这个加密过程是不可逆转的,和UNIX密码加密过程使用不同的算法。

六、控制流函数            
    CASE WHEN[test1] THEN [result1]...ELSE [default] END
        如果testN是真,则返回resultN,否则返回default
    CASE [test] WHEN[val1] THEN [result]...ELSE [default]END  
        如果test和valN相等,则返回resultN,否则返回default

    IF(test,t,f)   
        如果test是真,返回t;否则返回f

    IFNULL(arg1,arg2) 
        如果arg1不是空,返回arg1,否则返回arg2

    NULLIF(arg1,arg2) 
        如果arg1=arg2返回NULL;否则返回arg1        

七、控制流函数小练习
#7.1、准备表
/*
Navicat MySQL Data Transfer

Source Server         : localhost_3306
Source Server Version : 50720
Source Host           : localhost:3306
Source Database       : student

Target Server Type    : MYSQL
Target Server Version : 50720
File Encoding         : 65001

Date: 2018-01-02 12:05:30
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for course
-- ----------------------------
DROP TABLE IF EXISTS `course`;
CREATE TABLE `course` (
  `c_id` int(11) NOT NULL,
  `c_name` varchar(255) DEFAULT NULL,
  `t_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`c_id`),
  KEY `t_id` (`t_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of course
-- ----------------------------
INSERT INTO `course` VALUES ('1', 'python', '1');
INSERT INTO `course` VALUES ('2', 'java', '2');
INSERT INTO `course` VALUES ('3', 'linux', '3');
INSERT INTO `course` VALUES ('4', 'web', '2');

-- ----------------------------
-- Table structure for score
-- ----------------------------
DROP TABLE IF EXISTS `score`;
CREATE TABLE `score` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `s_id` int(10) DEFAULT NULL,
  `c_id` int(11) DEFAULT NULL,
  `num` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of score
-- ----------------------------
INSERT INTO `score` VALUES ('1', '1', '1', '79');
INSERT INTO `score` VALUES ('2', '1', '2', '78');
INSERT INTO `score` VALUES ('3', '1', '3', '35');
INSERT INTO `score` VALUES ('4', '2', '2', '32');
INSERT INTO `score` VALUES ('5', '3', '1', '66');
INSERT INTO `score` VALUES ('6', '4', '2', '77');
INSERT INTO `score` VALUES ('7', '4', '1', '68');
INSERT INTO `score` VALUES ('8', '5', '1', '66');
INSERT INTO `score` VALUES ('9', '2', '1', '69');
INSERT INTO `score` VALUES ('10', '4', '4', '75');
INSERT INTO `score` VALUES ('11', '5', '4', '66.7');

-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `s_id` varchar(20) NOT NULL,
  `s_name` varchar(255) DEFAULT NULL,
  `s_age` int(10) DEFAULT NULL,
  `s_sex` char(1) DEFAULT NULL,
  PRIMARY KEY (`s_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('1', '鲁班', '12', '男');
INSERT INTO `student` VALUES ('2', '貂蝉', '20', '女');
INSERT INTO `student` VALUES ('3', '刘备', '35', '男');
INSERT INTO `student` VALUES ('4', '关羽', '34', '男');
INSERT INTO `student` VALUES ('5', '张飞', '33', '女');

-- ----------------------------
-- Table structure for teacher
-- ----------------------------
DROP TABLE IF EXISTS `teacher`;
CREATE TABLE `teacher` (
  `t_id` int(10) NOT NULL,
  `t_name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`t_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of teacher
-- ----------------------------
INSERT INTO `teacher` VALUES ('1', '大王');
INSERT INTO `teacher` VALUES ('2', 'alex');
INSERT INTO `teacher` VALUES ('3', 'egon');
INSERT INTO `teacher` VALUES ('4', 'peiqi');

#7.2、统计各科各分数段人数.显示格式:课程ID,课程名称,[100-85],[85-70],[70-60],[ <60]

select  score.c_id,
          course.c_name, 
      sum(CASE WHEN num BETWEEN 85 and 100 THEN 1 ELSE 0 END) as '[100-85]',
      sum(CASE WHEN num BETWEEN 70 and 85 THEN 1 ELSE 0 END) as '[85-70]',
      sum(CASE WHEN num BETWEEN 60 and 70 THEN 1 ELSE 0 END) as '[70-60]',
      sum(CASE WHEN num < 60 THEN 1 ELSE 0 END) as '[ <60]'
from score,course where score.c_id=course.c_id GROUP BY score.c_id;

转载于:https://blog.51cto.com/10983441/2399811

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值