zoukankan      html  css  js  c++  java
  • 表操作--数据类型--表的完整性约束--修改表--数据操作--索引--数据备份(pymysql模块)--视图、触发器、事务、存储过程、函数

    表介绍

    表相当于文件,表中的一条记录就相当于文件的一行内容,不同的是,表中的一条记录有对应的标题,称为表的字段

    id,name,qq,age称为字段,其余的,一行内容称为一条记录

    本节重点:

    1 创建表

    2 查看表结构

    3 数据类型

    4 表完整性约束

    5 修改表

    6 复制表

    7 删除表

    一 创建表

    复制代码
    语法:
    create table 表名(
    字段名1 类型[(宽度) 约束条件],
    字段名2 类型[(宽度) 约束条件],
    字段名3 类型[(宽度) 约束条件]
    );
    
    注意:
    1. 在同一张表中,字段名是不能相同
    2. 宽度和约束条件可选
    3. 字段名和类型是必须的
    #1 操作文件夹(库)
        增
            create database db1 charset utf8;
    
        查
            show databases;
            show create database db1;
        改
            alter database db1 charset gbk;
        删
            drop database db1;
    
    #2 操作文件(表)
        切换到文件夹下:use db1
    
        增
            create table t1(id int,name char(10))engine=innodb;
            create table t2(id int,name char(10))engine=innodb default charset utf8;
        查
            show tables;
            show create table t1;
    
            desc t1;#查看表结构
        改
            alter table t1 add age int;
            alter table t1 modify name char(12);
    
        删
            drop table t1;
    
    #3 操作文件的一行行内容(记录)
        增
            insert into db1.t1 values(1,'egon1'),(2,'egon2'),(3,'egon3');
            insert into db1.t1(name) values('egon1'),('egon2'),('egon3');
        查
            select * from t1;
            select name from t1;
            select name,id from t1;
        改
            update t1 set name='SB' where id=4;
            update t1 set name='SB' where name='alex';
        删
            delete from t1 where id=4;
    
    
            #对于清空表记录有两种方式,但是推荐后者
            delete from t1;
            truncate t1; #当数据量比较大的情况下,使用这种方式,删除速度快
    
    
    
        #自增id
        create table t5(id int primary key auto_increment,name char(10));
        create table t4(id int not null unique,name char(10));
    
    insert into t5(name) values
    ('egon5'),
    ('egon6'),
    ('egon7'),
    ('egon8'),
    ('egon9'),
    ('egon10'),
    ('egon11'),
    ('egon12'),
    ('egon13');
    
    #拷贝表结构
    create table t7 select * from t5 where 1=2;
    alter table t7 modify id int primary key auto_increment;
    
    insert into t7(name) values
    ('egon1'),
    ('egon2'),
    ('egon3'),
    ('egon4'),
    ('egon5'),
    ('egon6'),
    ('egon7'),
    ('egon8'),
    ('egon9'),
    ('egon10'),
    ('egon11'),
    ('egon12'),
    ('egon13');
    
    
    delete from t7 where  id=1; #删记录
    update t7 set name=''; #修改字段对应的值

    权限问题:创建用户,然后重新打开一个cmd,选择之前创建好的用户名和密码登录,实现功能

    #创建用户
    create user 'lin'@'localhost' identified by '123';(只能在本机上,登录该用户)
    create user 'lin'@'%'identified by '123'(所有人都可以登录该用户) create user 'lin'@'192.168.20.%' by '123'(就是说在这个局域网的计算机可以是有该用户登录)
    登录时一定要输入该机器的网段
    mysql -h192.168.20.97 -ulin -p123(这里的ip-)
    #insert,delele,update,select #级别1:对所有库,下的所有表,下的所有字段 grant select on *.* to 'lin1'@'localhost' identified by '123'; #级别2:对db1库,下的所有表,下的所有字段 grant select on db1.* to 'lin2'@'localhost' identified by '123'; #级别3:对表db1.t1,下的所有字段 grant select on db1.t1 to 'lin3'@'localhost' identified by '123'; #级别4:对表db1.t1,下的id,name字段 grant select (id,name) on db1.t1 to 'lin4'@'localhost' identified by '123'; grant select (id,name),update (name) on db1.t1 to 'lin5'@'localhost' identified by '123'; #修改完权限后,要记得刷新权限 flush privileges;

    mysql四-1:数据类型

     

    一 介绍

    存储引擎决定了表的类型,而表内存放的数据也要有不同的类型,每种数据类型都有自己的宽度,但宽度是可选的

    详细参考:

    • http://www.runoob.com/mysql/mysql-data-types.html
    • http://dev.mysql.com/doc/refman/5.7/en/data-type-overview.html

    mysql数据类型概览

     View Code

    二 数值类型

          整数类型:TINYINT SMALLINT MEDIUMINT INT BIGINT

      作用:存储年龄,等级,id,各种号码等

     View Code
     验证

     !!!注意:为该类型指定宽度时,仅仅只是指定查询结果的显示宽度,与存储范围无关,存储范围如下

           其实我们完全没必要为整数类型指定显示宽度,使用默认的就可以了

           默认的显示宽度,都是在最大值的基础上加1

    int的存储宽度是4个Bytes,即32个bit,即2**32

    无符号最大值为:4294967296-1

    有符号最大值:2147483648-1

    有符号和无符号的最大数字需要的显示宽度均为10,而针对有符号的最小值则需要11位才能显示完全,所以int类型默认的显示宽度为11是非常合理的

    最后:整形类型,其实没有必要指定显示宽度,使用默认的就ok

      

      定点数类型  DEC等同于DECIMAL  

      浮点类型:FLOAT DOUBLE

      作用:存储薪资、身高、体重、体质参数等

    复制代码
    ======================================
            decimal[(m[,d])] [unsigned] [zerofill]
                准确的小数值,m是数字总个数(负号不算),d是小数点后个数。 m最大值为65,d最大值为30。
    
                特别的:对于精确数值计算时需要用此类型
                       decaimal能够存储精确值的原因在于其内部按照字符串存储。
    
    
    
    ======================================
            FLOAT[(M,D)] [UNSIGNED] [ZEROFILL]
                单精度浮点数(非准确小数值),m是数字总个数,d是小数点后个数。
                    有符号:
                        -3.402823466E+38 to -1.175494351E-38,
                        0
                        1.175494351E-38 to 3.402823466E+38
                    无符号:
                        0
                        1.175494351E-38 to 3.402823466E+38
    
                **** 数值越大,越不准确 ****
    
    
    ======================================
            DOUBLE[(M,D)] [UNSIGNED] [ZEROFILL]
                双精度浮点数(非准确小数值),m是数字总个数,d是小数点后个数。
    
                    有符号:
                        -1.7976931348623157E+308 to -2.2250738585072014E-308
                        0
                        2.2250738585072014E-308 to 1.7976931348623157E+308
                    无符号:
                        0
                        2.2250738585072014E-308 to 1.7976931348623157E+308
                **** 数值越大,越不准确 ****
    复制代码
    复制代码
    MariaDB [db1]> create table t8(salary float(5,2)); #总共5位,小数部分占2位,因而整数部分最多3位
    MariaDB [db1]> insert into t8 values
        -> (3.3),
        -> (7.33),
        -> (9.335),
        -> (1000.1);
    MariaDB [db1]> select * from t8;
    +--------+
    | salary |
    +--------+
    |   3.30 |
    |   7.33 |
    |   9.34 | #4舍5入
    | 999.99 | #小数最多2位,整数最多3位
    +--------+
    复制代码

      

      位类型:BIT

      BIT(M)可以用来存放多位二进制数,M范围从1~64,如果不写默认为1位。
      注意:对于位字段需要使用函数读取
          bin()显示为二进制
          hex()显示为十六进制

    复制代码
    MariaDB [db1]> create table t9(id bit);
    MariaDB [db1]> desc t9; #bit默认宽度为1
    +-------+--------+------+-----+---------+-------+
    | Field | Type   | Null | Key | Default | Extra |
    +-------+--------+------+-----+---------+-------+
    | id    | bit(1) | YES  |     | NULL    |       |
    +-------+--------+------+-----+---------+-------+
    
    MariaDB [db1]> insert into t9 values(8);
    MariaDB [db1]> select * from t9; #直接查看是无法显示二进制位的
    +------+
    | id   |
    +------+
    |     |
    +------+
    MariaDB [db1]> select bin(id),hex(id) from t9; #需要转换才能看到
    +---------+---------+
    | bin(id) | hex(id) |
    +---------+---------+
    | 1       | 1       |
    +---------+---------+
    
    MariaDB [db1]> alter table t9 modify id bit(5);
    MariaDB [db1]> insert into t9 values(8);
    MariaDB [db1]> select bin(id),hex(id) from t9;
    +---------+---------+
    | bin(id) | hex(id) |
    +---------+---------+
    | 1       | 1       |
    | 1000    | 8       |
    +---------+---------+
    复制代码

    三 日期类型

    DATE TIME DATETIME TIMESTAMP YEAR 

    作用:存储用户注册时间,文章发布时间,员工入职时间,出生时间,过期时间等

    复制代码
            YEAR
                YYYY(1901/2155)
    
            DATE
                YYYY-MM-DD(1000-01-01/9999-12-31)
    
            TIME
                HH:MM:SS('-838:59:59'/'838:59:59')
    
            DATETIME
    
                YYYY-MM-DD HH:MM:SS(1000-01-01 00:00:00/9999-12-31 23:59:59    Y)
    
            TIMESTAMP
    
                YYYYMMDD HHMMSS(1970-01-01 00:00:00/2037 年某时)
    复制代码
    复制代码
    ============year===========
    MariaDB [db1]> create table t10(born_year year); #无论year指定何种宽度,最后都默认是year(4)
    MariaDB [db1]> insert into t10 values  
        -> (1900),
        -> (1901),
        -> (2155),
        -> (2156);
    MariaDB [db1]> select * from t10;
    +-----------+
    | born_year |
    +-----------+
    |      0000 |
    |      1901 |
    |      2155 |
    |      0000 |
    +-----------+
    
    
    ============date,time,datetime===========
    MariaDB [db1]> create table t11(d date,t time,dt datetime);
    MariaDB [db1]> desc t11;
    +-------+----------+------+-----+---------+-------+
    | Field | Type     | Null | Key | Default | Extra |
    +-------+----------+------+-----+---------+-------+
    | d     | date     | YES  |     | NULL    |       |
    | t     | time     | YES  |     | NULL    |       |
    | dt    | datetime | YES  |     | NULL    |       |
    +-------+----------+------+-----+---------+-------+
    
    MariaDB [db1]> insert into t11 values(now(),now(),now());
    MariaDB [db1]> select * from t11;
    +------------+----------+---------------------+
    | d          | t        | dt                  |
    +------------+----------+---------------------+
    | 2017-07-25 | 16:26:54 | 2017-07-25 16:26:54 |
    +------------+----------+---------------------+
    
    
    
    ============timestamp===========
    MariaDB [db1]> create table t12(time timestamp);
    MariaDB [db1]> insert into t12 values();
    MariaDB [db1]> insert into t12 values(null);
    MariaDB [db1]> select * from t12;
    +---------------------+
    | time                |
    +---------------------+
    | 2017-07-25 16:29:17 |
    | 2017-07-25 16:30:01 |
    +---------------------+
    
    
    
    ============注意啦,注意啦,注意啦===========
    1. 单独插入时间时,需要以字符串的形式,按照对应的格式插入
    2. 插入年份时,尽量使用4位值
    3. 插入两位年份时,<=69,以20开头,比如50,  结果2050      
                    >=70,以19开头,比如71,结果1971
    MariaDB [db1]> create table t12(y year);
    MariaDB [db1]> insert into t12 values  
        -> (50),
        -> (71);
    MariaDB [db1]> select * from t12;
    +------+
    | y    |
    +------+
    | 2050 |
    | 1971 |
    +------+
    
    
    
    ============综合练习===========
    MariaDB [db1]> create table student(
        -> id int,
        -> name varchar(20),
        -> born_year year,
        -> birth date,
        -> class_time time,
        -> reg_time datetime);
    
    MariaDB [db1]> insert into student values
        -> (1,'alex',"1995","1995-11-11","11:11:11","2017-11-11 11:11:11"),
        -> (2,'egon',"1997","1997-12-12","12:12:12","2017-12-12 12:12:12"),
        -> (3,'wsb',"1998","1998-01-01","13:13:13","2017-01-01 13:13:13");
    
    MariaDB [db1]> select * from student;
    +------+------+-----------+------------+------------+---------------------+
    | id   | name | born_year | birth      | class_time | reg_time            |
    +------+------+-----------+------------+------------+---------------------+
    |    1 | alex |      1995 | 1995-11-11 | 11:11:11   | 2017-11-11 11:11:11 |
    |    2 | egon |      1997 | 1997-12-12 | 12:12:12   | 2017-12-12 12:12:12 |
    |    3 | wsb  |      1998 | 1998-01-01 | 13:13:13   | 2017-01-01 13:13:13 |
    +------+------+-----------+------------+------------+---------------------+
    复制代码
    复制代码
    在实际应用的很多场景中,MySQL的这两种日期类型都能够满足我们的需要,存储精度都为秒,但在某些情况下,会展现出他们各自的优劣。下面就来总结一下两种日期类型的区别。
    
    1.DATETIME的日期范围是1001——9999年,TIMESTAMP的时间范围是1970——2038年。
    
    2.DATETIME存储时间与时区无关,TIMESTAMP存储时间与时区有关,显示的值也依赖于时区。在mysql服务器,操作系统以及客户端连接都有时区的设置。
    
    3.DATETIME使用8字节的存储空间,TIMESTAMP的存储空间为4字节。因此,TIMESTAMP比DATETIME的空间利用率更高。
    
    4.DATETIME的默认值为null;TIMESTAMP的字段默认不为空(not null),默认值为当前时间(CURRENT_TIMESTAMP),如果不做特殊处理,并且update语句中没有指定该列的更新值,则默认更新为当前时间。
    复制代码

    四 字符串类型

    复制代码
    #官网:https://dev.mysql.com/doc/refman/5.7/en/char.html
    #注意:char和varchar括号内的参数指的都是字符的长度
    
    #char类型:定长,简单粗暴,浪费空间,存取速度快
        字符长度范围:0-255(一个中文是一个字符,是utf8编码的3个字节)
        存储:
            存储char类型的值时,会往右填充空格来满足长度
            例如:指定长度为10,存>10个字符则报错,存<10个字符则用空格填充直到凑够10个字符存储
    
        检索:
            在检索或者说查询时,查出的结果会自动删除尾部的空格,除非我们打开pad_char_to_full_length SQL模式(SET sql_mode = 'PAD_CHAR_TO_FULL_LENGTH';)
    
    #varchar类型:变长,精准,节省空间,存取速度慢
        字符长度范围:0-65535(如果大于21845会提示用其他类型 。mysql行最大限制为65535字节,字符编码为utf-8:https://dev.mysql.com/doc/refman/5.7/en/column-count-limit.html)
        存储:
            varchar类型存储数据的真实内容,不会用空格填充,如果'ab  ',尾部的空格也会被存起来
            强调:varchar类型会在真实数据前加1-2Bytes的前缀,该前缀用来表示真实数据的bytes字节数(1-2Bytes最大表示65535个数字,正好符合mysql对row的最大字节限制,即已经足够使用)
            如果真实的数据<255bytes则需要1Bytes的前缀(1Bytes=8bit 2**8最大表示的数字为255)
            如果真实的数据>255bytes则需要2Bytes的前缀(2Bytes=16bit 2**16最大表示的数字为65535)
        
        检索:
            尾部有空格会保存下来,在检索或者说查询时,也会正常显示包含空格在内的内容
    复制代码
     官网详解
    ValueCHAR(4)Storage RequiredVARCHAR(4)Storage Required
    '' '    ' 4 bytes '' 1 byte
    'ab' 'ab  ' 4 bytes 'ab' 3 bytes
    'abcd' 'abcd' 4 bytes 'abcd' 5 bytes
    'abcdefgh' 'abcd' 4 bytes 'abcd' 5 bytes
    测试前了解两个函数
    length:查看字节数
    char_length:查看字符数

    1. char填充空格来满足固定长度,但是在查询时却会很不要脸地删除尾部的空格(装作自己好像没有浪费过空间一样),然后修改sql_mode让其现出原形

    复制代码
    mysql> create table t1(x char(5),y varchar(5));
    Query OK, 0 rows affected (0.26 sec)
    
    #char存5个字符,而varchar存4个字符
    mysql> insert into t1 values('你瞅啥 ','你瞅啥 ');
    Query OK, 1 row affected (0.05 sec)
    
    mysql> SET sql_mode='';
    Query OK, 0 rows affected, 1 warning (0.00 sec)
    
    #在检索时char很不要脸地将自己浪费的2个字符给删掉了,装的好像自己没浪费过空间一样,而varchar很老实,存了多少,就显示多少
    mysql> select x,char_length(x),y,char_length(y) from t1; 
    +-----------+----------------+------------+----------------+
    | x         | char_length(x) | y          | char_length(y) |
    +-----------+----------------+------------+----------------+
    | 你瞅啥    |              3 | 你瞅啥     |              4 |
    +-----------+----------------+------------+----------------+
    1 row in set (0.00 sec)
    
    #略施小计,让char现出原形
    mysql> SET sql_mode = 'PAD_CHAR_TO_FULL_LENGTH';
    Query OK, 0 rows affected (0.00 sec)
    
    #这下子char原形毕露了......
    mysql> select x,char_length(x),y,char_length(y) from t1;
    +-------------+----------------+------------+----------------+
    | x           | char_length(x) | y          | char_length(y) |
    +-------------+----------------+------------+----------------+
    | 你瞅啥      |              5 | 你瞅啥     |              4 |
    +-------------+----------------+------------+----------------+
    1 row in set (0.00 sec)
    
    
    #char类型:3个中文字符+2个空格=11Bytes
    #varchar类型:3个中文字符+1个空格=10Bytes
    mysql> select x,length(x),y,length(y) from t1;
    +-------------+-----------+------------+-----------+
    | x           | length(x) | y          | length(y) |
    +-------------+-----------+------------+-----------+
    | 你瞅啥      |        11 | 你瞅啥     |        10 |
    +-------------+-----------+------------+-----------+
    1 row in set (0.00 sec)
    复制代码
    复制代码
    mysql> select concat('数据: ',x,'长度: ',char_length(x)),concat(y,char_length(y)
    ) from t1;
    +------------------------------------------------+--------------------------+
    | concat('数据: ',x,'长度: ',char_length(x))     | concat(y,char_length(y)) |
    +------------------------------------------------+--------------------------+
    | 数据: 你瞅啥  长度: 5                          | 你瞅啥 4                 |
    +------------------------------------------------+--------------------------+
    1 row in set (0.00 sec)
    复制代码

    2. 虽然 CHAR 和 VARCHAR 的存储方式不太相同,但是对于两个字符串的比较,都只比 较其值,忽略 CHAR 值存在的右填充,即使将 SQL _MODE 设置为 PAD_CHAR_TO_FULL_ LENGTH 也一样,,但这不适用于like

    复制代码
    Values in CHAR and VARCHAR columns are sorted and compared according to the character set collation assigned to the column.
    
    All MySQL collations are of type PAD SPACE. This means that all CHAR, VARCHAR, and TEXT values are compared without regard to any trailing spaces. “Comparison” in this context does not include the LIKE pattern-matching operator, for which trailing spaces are significant. For example:
    
    mysql> CREATE TABLE names (myname CHAR(10));
    Query OK, 0 rows affected (0.03 sec)
    
    mysql> INSERT INTO names VALUES ('Monty');
    Query OK, 1 row affected (0.00 sec)
    
    mysql> SELECT myname = 'Monty', myname = 'Monty  ' FROM names;
    +------------------+--------------------+
    | myname = 'Monty' | myname = 'Monty  ' |
    +------------------+--------------------+
    |                1 |                  1 |
    +------------------+--------------------+
    1 row in set (0.00 sec)
    
    mysql> SELECT myname LIKE 'Monty', myname LIKE 'Monty  ' FROM names;
    +---------------------+-----------------------+
    | myname LIKE 'Monty' | myname LIKE 'Monty  ' |
    +---------------------+-----------------------+
    |                   1 |                     0 |
    +---------------------+-----------------------+
    1 row in set (0.00 sec)
    复制代码

    3. 总结

    复制代码
    #常用字符串系列:char与varchar
    注:虽然varchar使用起来较为灵活,但是从整个系统的性能角度来说,char数据类型的处理速度更快,有时甚至可以超出varchar处理速度的50%。因此,用户在设计数据库时应当综合考虑各方面的因素,以求达到最佳的平衡
    
    #其他字符串系列(效率:char>varchar>text)
    TEXT系列 TINYTEXT TEXT MEDIUMTEXT LONGTEXT
    BLOB 系列    TINYBLOB BLOB MEDIUMBLOB LONGBLOB 
    BINARY系列 BINARY VARBINARY
    
    text:text数据类型用于保存变长的大字符串,可以组多到65535 (2**16 − 1)个字符。
    mediumtext:A TEXT column with a maximum length of 16,777,215 (2**24 − 1) characters.
    longtext:A TEXT column with a maximum length of 4,294,967,295 or 4GB (2**32 − 1) characters.
    复制代码

    五 枚举类型与集合类型

    字段的值只能在给定范围中选择,如单选框,多选框
    enum 单选 只能在给定的范围内选一个值,如性别 sex 男male/女female
    set 多选 在给定的范围内可以选择一个或一个以上的值(爱好1,爱好2,爱好3...)

    create table student1(
    id int primary key auto_increment,
    name char(5),
    sex enum('male','female'),
    hobbies set('music','read','study','coding')
    );
    
    insert into student1(name,sex,hobbies) values('egon','None','asdfasdfasdf');
    insert into student1(name,sex,hobbies) values('egon','male','music,read');

    数据实例:

    1 数字(默认都是有符号,宽度指的是显示宽度,与存储无关)
        tinyint int bigint:个数,年龄,id,qq号,手机号
        float:价格,身高,体重,余额
    
    2 字符(宽度指的是字符个数):姓名,性别,职业,地址,职称,介绍
        char:简单粗暴,不够则凑够固定长度存放起来,浪费空间,存取速度快
        varchar:精准,计算出待存放的数据的长度,节省空间,存取速度慢
    
    3 日期
        #注册时间
        datetime 2017-09-06 10:39:49
    
        #出生年月日,开学时间
        date:2017-09-06
    
        #聊天记录,上课时间
        time:10:39:49
    
        #出生年
        year:2017
    
    
    4 枚举与集合
    enum枚举:规定一个范围,可有多个值,但是为该字段传值时,只能取规定范围中的一个
    set集合:规定一个范围,可有多个值,但是为该字段传值时,可以取规定范围中的一个或多个
    
    1 :
    #整型测试
    create table t1(id tinyint);
    create table t2(id int);
    create table t3(id bigint);
    
    #浮点型测试
    0.1231233123412 3123213123123123
    
    float:0.1231233123412 0000000000000000
    double:0.1231233123412 3123213123100000
    decimal:
    
    #测试
    create table t4(salary float(5,2));
    insert into t4 values (3.73555);
    insert into t4 values (-3.73555);
    insert into t4 values (-1111.73555);
    insert into t4 values (-111.73555);
    
    
    2 char与varchar测试()
    create table t6(name char(4));
    insert into t6 values('alexsb');
    insert into t6 values('欧德博爱');
    insert into t6 values('艾利克斯a');
    
    create table t7(x char(5),y varchar(5));
    #insert into t7 values('abcdef','abc');
    #insert into t7 values('abc','abc');
    #insert into t7 values('abc','abcdef');
    
    insert into t7 values('abc','abc'); #char_length :查看字符的长度
    insert into t7 values('你好啊','好你妹'); #char_length :查看字符的长度
    #了解
    insert into t7 values('你好啊','好你妹'); #length:查看字节的长度
    
    
    #注意两点:
    insert into t7 values('abc ','abc '); #length:查看字节的长度
    select * from t7 where y='abc    '; #去掉末尾的空格然后去比较
    
    
    3:日期类型
    create table student(
    id int,
    name char(5),
    born_date date,
    born_year year,
    reg_time datetime,
    class_time time
    );
    
    insert into student values(1,'alex',now(),now(),now(),now());
    insert into student values(1,'alex','2017-09-06','2017','2017-09-06 10:39:00','08:30:00');
    
    #了解
    insert into student values(1,'alex','2017-09-06',2017,'2017-09-06 10:39:00','08:30:00');
    insert into student values(1,'alex','2017/09/06',2017,'2017-09-06 10:39:00','08:30:00');
    insert into student values(1,'alex','20170906',2017,'20170906103900','083000');
    
    
    4 枚举与集合
    create table student1(
    id int primary key auto_increment,
    name char(5),
    sex enum('male','female'),
    hobbies set('music','read','study','coding')
    );
    
    insert into student1(name,sex,hobbies) values('egon','None','asdfasdfasdf');
    insert into student1(name,sex,hobbies) values('egon','male','music,read');

    表的完整性约束

    mysql四-2:完整性约束

     

    一 介绍

    约束条件与数据类型的宽度一样,都是可选参数

    作用:用于保证数据的完整性和一致性
    主要分为:

    复制代码
    PRIMARY KEY (PK)    标识该字段为该表的主键,可以唯一的标识记录
    FOREIGN KEY (FK)    标识该字段为该表的外键
    NOT NULL    标识该字段不能为空
    UNIQUE KEY (UK)    标识该字段的值是唯一的
    AUTO_INCREMENT    标识该字段的值自动增长(整数类型,而且为主键)
    DEFAULT    为该字段设置默认值
    
    UNSIGNED 无符号
    ZEROFILL 使用0填充
    复制代码

    说明:

    复制代码
    1. 是否允许为空,默认NULL,可设置NOT NULL,字段不允许为空,必须赋值
    2. 字段是否有默认值,缺省的默认值是NULL,如果插入记录时不给字段赋值,此字段使用默认值
    sex enum('male','female') not null default 'male'
    age int unsigned NOT NULL default 20 必须为正值(无符号) 不允许为空 默认是20
    3. 是否是key
    主键 primary key
    外键 foreign key
    索引 (index,unique...)
    复制代码

    二 not null与default

    是否可空,null表示空,非字符串
    not null - 不可空
    null - 可空


    默认值,创建列时可以指定默认值,当插入数据时如果未主动设置,则自动添加默认值
    create table tb1(
    nid int not null defalut 2,
    num int not null
    )

    复制代码
    ==================not null====================
    mysql> create table t1(id int); #id字段默认可以插入空
    mysql> desc t1;
    +-------+---------+------+-----+---------+-------+
    | Field | Type    | Null | Key | Default | Extra |
    +-------+---------+------+-----+---------+-------+
    | id    | int(11) | YES  |     | NULL    |       |
    +-------+---------+------+-----+---------+-------+
    mysql> insert into t1 values(); #可以插入空
    
    
    mysql> create table t2(id int not null); #设置字段id不为空
    mysql> desc t2;
    +-------+---------+------+-----+---------+-------+
    | Field | Type    | Null | Key | Default | Extra |
    +-------+---------+------+-----+---------+-------+
    | id    | int(11) | NO   |     | NULL    |       |
    +-------+---------+------+-----+---------+-------+
    mysql> insert into t2 values(); #不能插入空
    ERROR 1364 (HY000): Field 'id' doesn't have a default value
    
    
    
    ==================default====================
    #设置id字段有默认值后,则无论id字段是null还是not null,都可以插入空,插入空默认填入default指定的默认值
    mysql> create table t3(id int default 1);
    mysql> alter table t3 modify id int not null default 1;
    
    
    
    ==================综合练习====================
    mysql> create table student(
        -> name varchar(20) not null,
        -> age int(3) unsigned not null default 18,
        -> sex enum('male','female') default 'male',
        -> hobby set('play','study','read','music') default 'play,music'
        -> );
    mysql> desc student;
    +-------+------------------------------------+------+-----+------------+-------+
    | Field | Type                               | Null | Key | Default    | Extra |
    +-------+------------------------------------+------+-----+------------+-------+
    | name  | varchar(20)                        | NO   |     | NULL       |       |
    | age   | int(3) unsigned                    | NO   |     | 18         |       |
    | sex   | enum('male','female')              | YES  |     | male       |       |
    | hobby | set('play','study','read','music') | YES  |     | play,music |       |
    +-------+------------------------------------+------+-----+------------+-------+
    mysql> insert into student(name) values('egon');
    mysql> select * from student;
    +------+-----+------+------------+
    | name | age | sex  | hobby      |
    +------+-----+------+------------+
    | egon |  18 | male | play,music |
    +------+-----+------+------------+
    复制代码

    三 unique

    复制代码
    ============设置唯一约束 UNIQUE===============
    方法一:
    create table department1(
    id int,
    name varchar(20) unique,
    comment varchar(100)
    );
    
    
    方法二:
    create table department2(
    id int,
    name varchar(20),
    comment varchar(100),
    constraint uk_name unique(name)
    );
    
    
    mysql> insert into department1 values(1,'IT','技术');
    Query OK, 1 row affected (0.00 sec)
    mysql> insert into department1 values(1,'IT','技术');
    ERROR 1062 (23000): Duplicate entry 'IT' for key 'name'
    复制代码
    复制代码
    mysql> create table t1(id int not null unique);
    Query OK, 0 rows affected (0.02 sec)
    
    mysql> desc t1;
    +-------+---------+------+-----+---------+-------+
    | Field | Type    | Null | Key | Default | Extra |
    +-------+---------+------+-----+---------+-------+
    | id    | int(11) | NO   | PRI | NULL    |       |
    +-------+---------+------+-----+---------+-------+
    1 row in set (0.00 sec)
    复制代码
    复制代码
    create table service(
    id int primary key auto_increment,
    name varchar(20),
    host varchar(15) not null,
    port int not null,
    unique(host,port) #联合唯一
    );
    
    mysql> insert into service values
        -> (1,'nginx','192.168.0.10',80),
        -> (2,'haproxy','192.168.0.20',80),
        -> (3,'mysql','192.168.0.30',3306)
        -> ;
    Query OK, 3 rows affected (0.01 sec)
    Records: 3  Duplicates: 0  Warnings: 0
    
    mysql> insert into service(name,host,port) values('nginx','192.168.0.10',80);
    ERROR 1062 (23000): Duplicate entry '192.168.0.10-80' for key 'host'
    复制代码

    四 primary key

    primary key字段的值不为空且唯一

    一个表中可以:

    单列做主键
    多列做主键(复合主键)

    但一个表内只能有一个主键primary key

    复制代码
    ============单列做主键===============
    #方法一:not null+unique
    create table department1(
    id int not null unique, #主键
    name varchar(20) not null unique,
    comment varchar(100)
    );
    
    mysql> desc department1;
    +---------+--------------+------+-----+---------+-------+
    | Field   | Type         | Null | Key | Default | Extra |
    +---------+--------------+------+-----+---------+-------+
    | id      | int(11)      | NO   | PRI | NULL    |       |
    | name    | varchar(20)  | NO   | UNI | NULL    |       |
    | comment | varchar(100) | YES  |     | NULL    |       |
    +---------+--------------+------+-----+---------+-------+
    rows in set (0.01 sec)
    
    #方法二:在某一个字段后用primary key
    create table department2(
    id int primary key, #主键
    name varchar(20),
    comment varchar(100)
    );
    
    mysql> desc department2;
    +---------+--------------+------+-----+---------+-------+
    | Field   | Type         | Null | Key | Default | Extra |
    +---------+--------------+------+-----+---------+-------+
    | id      | int(11)      | NO   | PRI | NULL    |       |
    | name    | varchar(20)  | YES  |     | NULL    |       |
    | comment | varchar(100) | YES  |     | NULL    |       |
    +---------+--------------+------+-----+---------+-------+
    rows in set (0.00 sec)
    
    #方法三:在所有字段后单独定义primary key
    create table department3(
    id int,
    name varchar(20),
    comment varchar(100),
    constraint pk_name primary key(id); #创建主键并为其命名pk_name
    
    mysql> desc department3;
    +---------+--------------+------+-----+---------+-------+
    | Field   | Type         | Null | Key | Default | Extra |
    +---------+--------------+------+-----+---------+-------+
    | id      | int(11)      | NO   | PRI | NULL    |       |
    | name    | varchar(20)  | YES  |     | NULL    |       |
    | comment | varchar(100) | YES  |     | NULL    |       |
    +---------+--------------+------+-----+---------+-------+
    rows in set (0.01 sec)
    复制代码
    复制代码
    ==================多列做主键================
    create table service(
    ip varchar(15),
    port char(5),
    service_name varchar(10) not null,
    primary key(ip,port)
    );
    
    
    mysql> desc service;
    +--------------+-------------+------+-----+---------+-------+
    | Field        | Type        | Null | Key | Default | Extra |
    +--------------+-------------+------+-----+---------+-------+
    | ip           | varchar(15) | NO   | PRI | NULL    |       |
    | port         | char(5)     | NO   | PRI | NULL    |       |
    | service_name | varchar(10) | NO   |     | NULL    |       |
    +--------------+-------------+------+-----+---------+-------+
    3 rows in set (0.00 sec)
    
    mysql> insert into service values
        -> ('172.16.45.10','3306','mysqld'),
        -> ('172.16.45.11','3306','mariadb')
        -> ;
    Query OK, 2 rows affected (0.00 sec)
    Records: 2  Duplicates: 0  Warnings: 0
    
    mysql> insert into service values ('172.16.45.10','3306','nginx');
    ERROR 1062 (23000): Duplicate entry '172.16.45.10-3306' for key 'PRIMARY'
    复制代码

    五 auto_increment

    约束字段为自动增长,被约束的字段必须同时被key约束

    复制代码
    #不指定id,则自动增长
    create table student(
    id int primary key auto_increment,
    name varchar(20),
    sex enum('male','female') default 'male'
    );
    
    mysql> desc student;
    +-------+-----------------------+------+-----+---------+----------------+
    | Field | Type                  | Null | Key | Default | Extra          |
    +-------+-----------------------+------+-----+---------+----------------+
    | id    | int(11)               | NO   | PRI | NULL    | auto_increment |
    | name  | varchar(20)           | YES  |     | NULL    |                |
    | sex   | enum('male','female') | YES  |     | male    |                |
    +-------+-----------------------+------+-----+---------+----------------+
    mysql> insert into student(name) values
        -> ('egon'),
        -> ('alex')
        -> ;
    
    mysql> select * from student;
    +----+------+------+
    | id | name | sex  |
    +----+------+------+
    |  1 | egon | male |
    |  2 | alex | male |
    +----+------+------+
    
    
    #也可以指定id
    mysql> insert into student values(4,'asb','female');
    Query OK, 1 row affected (0.00 sec)
    
    mysql> insert into student values(7,'wsb','female');
    Query OK, 1 row affected (0.00 sec)
    
    mysql> select * from student;
    +----+------+--------+
    | id | name | sex    |
    +----+------+--------+
    |  1 | egon | male   |
    |  2 | alex | male   |
    |  4 | asb  | female |
    |  7 | wsb  | female |
    +----+------+--------+
    
    
    #对于自增的字段,在用delete删除后,再插入值,该字段仍按照删除前的位置继续增长
    mysql> delete from student;
    Query OK, 4 rows affected (0.00 sec)
    
    mysql> select * from student;
    Empty set (0.00 sec)
    
    mysql> insert into student(name) values('ysb');
    mysql> select * from student;
    +----+------+------+
    | id | name | sex  |
    +----+------+------+
    |  8 | ysb  | male |
    +----+------+------+
    
    #应该用truncate清空表,比起delete一条一条地删除记录,truncate是直接清空表,在删除大表时用它
    mysql> truncate student;
    Query OK, 0 rows affected (0.01 sec)
    
    mysql> insert into student(name) values('egon');
    Query OK, 1 row affected (0.01 sec)
    
    mysql> select * from student;
    +----+------+------+
    | id | name | sex  |
    +----+------+------+
    |  1 | egon | male |
    +----+------+------+
    1 row in set (0.00 sec)
    复制代码
    复制代码
    #在创建完表后,修改自增字段的起始值
    mysql> create table student(
        -> id int primary key auto_increment,
        -> name varchar(20),
        -> sex enum('male','female') default 'male'
        -> );
    
    mysql> alter table student auto_increment=3;
    
    mysql> show create table student;
    .......
    ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
    
    mysql> insert into student(name) values('egon');
    Query OK, 1 row affected (0.01 sec)
    
    mysql> select * from student;
    +----+------+------+
    | id | name | sex  |
    +----+------+------+
    |  3 | egon | male |
    +----+------+------+
    row in set (0.00 sec)
    
    mysql> show create table student;
    .......
    ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
    
    
    #也可以创建表时指定auto_increment的初始值,注意初始值的设置为表选项,应该放到括号外
    create table student(
    id int primary key auto_increment,
    name varchar(20),
    sex enum('male','female') default 'male'
    )auto_increment=3;
    
    
    
    
    #设置步长
    sqlserver:自增步长
        基于表级别
        create table t1(
            id int。。。
        )engine=innodb,auto_increment=2 步长=2 default charset=utf8
    
    mysql自增的步长:
        show session variables like 'auto_inc%';
        
        #基于会话级别
        set session auth_increment_increment=2 #修改会话级别的步长
    
        #基于全局级别的
        set global auth_increment_increment=2 #修改全局级别的步长(所有会话都生效)
    
    
    #!!!注意了注意了注意了!!!
    If the value of auto_increment_offset is greater than that of auto_increment_increment, the value of auto_increment_offset is ignored. 
    翻译:如果auto_increment_offset的值大于auto_increment_increment的值,则auto_increment_offset的值会被忽略 
    比如:设置auto_increment_offset=3,auto_increment_increment=2
    
    
    
    
    mysql> set global auto_increment_increment=5;
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> set global auto_increment_offset=3;
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> show variables like 'auto_incre%'; #需要退出重新登录
    +--------------------------+-------+
    | Variable_name            | Value |
    +--------------------------+-------+
    | auto_increment_increment | 1     |
    | auto_increment_offset    | 1     |
    +--------------------------+-------+
    
    
    
    create table student(
    id int primary key auto_increment,
    name varchar(20),
    sex enum('male','female') default 'male'
    );
    
    mysql> insert into student(name) values('egon1'),('egon2'),('egon3');
    mysql> select * from student;
    +----+-------+------+
    | id | name  | sex  |
    +----+-------+------+
    |  3 | egon1 | male |
    |  8 | egon2 | male |
    | 13 | egon3 | male |
    +----+-------+------+
    复制代码

    六 foreign key

    员工信息表有三个字段:工号  姓名  部门

    公司有3个部门,但是有1个亿的员工,那意味着部门这个字段需要重复存储,部门名字越长,越浪费

    解决方法:

    我们完全可以定义一个部门表

    然后让员工信息表关联该表,如何关联,即foreign key

    复制代码
    #表类型必须是innodb存储引擎,且被关联的字段,即references指定的另外一个表的字段,必须保证唯一
    create table department(
    id int primary key,
    name varchar(20) not null
    )engine=innodb;
    
    #dpt_id外键,关联父表(department主键id),同步更新,同步删除
    create table employee(
    id int primary key,
    name varchar(20) not null,
    dpt_id int,
    constraint fk_name foreign key(dpt_id)
    references department(id)
    on delete cascade
    on update cascade 
    )engine=innodb;
    
    
    #先往父表department中插入记录
    insert into department values
    (1,'欧德博爱技术有限事业部'),
    (2,'艾利克斯人力资源部'),
    (3,'销售部');
    
    
    #再往子表employee中插入记录
    insert into employee values
    (1,'egon',1),
    (2,'alex1',2),
    (3,'alex2',2),
    (4,'alex3',2),
    (5,'李坦克',3),
    (6,'刘飞机',3),
    (7,'张火箭',3),
    (8,'林子弹',3),
    (9,'加特林',3)
    ;
    
    
    #删父表department,子表employee中对应的记录跟着删
    mysql> delete from department where id=3;
    mysql> select * from employee;
    +----+-------+--------+
    | id | name  | dpt_id |
    +----+-------+--------+
    |  1 | egon  |      1 |
    |  2 | alex1 |      2 |
    |  3 | alex2 |      2 |
    |  4 | alex3 |      2 |
    +----+-------+--------+
    
    
    #更新父表department,子表employee中对应的记录跟着改
    mysql> update department set id=22222 where id=2;
    mysql> select * from employee;
    +----+-------+--------+
    | id | name  | dpt_id |
    +----+-------+--------+
    |  1 | egon  |      1 |
    |  3 | alex2 |  22222 |
    |  4 | alex3 |  22222 |
    |  5 | alex1 |  22222 |
    +----+-------+--------+
    复制代码
    复制代码
    表1 foreign key 表2
    则表1的多条记录对应表2的一条记录,即多对一
    
    利用foreign key的原理我们可以制作两张表的多对多,一对一关系
    多对多:
        表1的多条记录可以对应表2的一条记录
        表2的多条记录也可以对应表1的一条记录
    
    一对一:
        表1的一条记录唯一对应表2的一条记录,反之亦然
    
    分析时,我们先从按照上面的基本原理去套,然后再翻译成真实的意义,就很好理解了
    复制代码
    #一对多或称为多对一
    三张表:出版社,作者信息,书
    
    一对多(或多对一):一个出版社可以出版多本书
    
    关联方式:foreign key
    复制代码
    =====================多对一=====================
    create table press(
    id int primary key auto_increment,
    name varchar(20)
    );
    
    create table book(
    id int primary key auto_increment,
    name varchar(20),
    press_id int not null,
    foreign key(press_id) references press(id)
    on delete cascade
    on update cascade
    );
    
    
    insert into press(name) values
    ('北京工业地雷出版社'),
    ('人民音乐不好听出版社'),
    ('知识产权没有用出版社')
    ;
    
    insert into book(name,press_id) values
    ('九阳神功',1),
    ('九阴真经',2),
    ('九阴白骨爪',2),
    ('独孤九剑',3),
    ('降龙十巴掌',2),
    ('葵花宝典',3)
    ;
    复制代码
     其他例子

      

    #多对多
    三张表:出版社,作者信息,书
    
    多对多:一个作者可以写多本书,一本书也可以有多个作者,双向的一对多,即多对多
      
    关联方式:foreign key+一张新的表
    复制代码
    =====================多对多=====================
    create table author(
    id int primary key auto_increment,
    name varchar(20)
    );
    
    
    #这张表就存放作者表与书表的关系,即查询二者的关系查这表就可以了
    create table author2book(
    id int not null unique auto_increment,
    author_id int not null,
    book_id int not null,
    constraint fk_author foreign key(author_id) references author(id)
    on delete cascade
    on update cascade,
    constraint fk_book foreign key(book_id) references book(id)
    on delete cascade
    on update cascade,
    primary key(author_id,book_id)
    );
    
    
    #插入四个作者,id依次排开
    insert into author(name) values('egon'),('alex'),('yuanhao'),('wpq');
    
    #每个作者与自己的代表作如下
    1 egon: 
          1 九阳神功
          2 九阴真经
          3 九阴白骨爪
          4 独孤九剑
          5 降龙十巴掌
          6 葵花宝典
    
    
    2 alex: 
          1 九阳神功
          6 葵花宝典
    
    3 yuanhao:
          4 独孤九剑
          5 降龙十巴掌
          6 葵花宝典
    
    4 wpq:
          1 九阳神功
    
    
    insert into author2book(author_id,book_id) values
    (1,1),
    (1,2),
    (1,3),
    (1,4),
    (1,5),
    (1,6),
    (2,1),
    (2,6),
    (3,4),
    (3,5),
    (3,6),
    (4,1)
    ;
    复制代码
    单张表:用户表+相亲关系表,相当于:用户表+相亲关系表+用户表
    多张表:用户表+用户与主机关系表+主机表
    
    中间那一张存放关系的表,对外关联的字段可以联合唯一
    #一对一
    两张表:学生表和客户表
    
    一对一:一个学生是一个客户,一个客户有可能变成一个学校,即一对一的关系
    
    关联方式:foreign key+unique
    复制代码
    #一定是student来foreign key表customer,这样就保证了:
    #1 学生一定是一个客户,
    #2 客户不一定是学生,但有可能成为一个学生
    
    
    create table customer(
    id int primary key auto_increment,
    name varchar(20) not null
    );
    
    
    create table student(
    id int primary key auto_increment,
    name varchar(20) not null,
    class_name varchar(20) not null default 'python自动化',
    level int default 1,
    customer_id int unique, #该字段一定要是唯一的
    foreign key(customer_id) references customer(id) #外键的字段一定要保证unique
    on delete cascade
    on update cascade
    );
    
    
    #增加客户
    insert into customer(name) values
    ('李飞机'),
    ('王大炮'),
    ('守榴弹'),
    ('吴坦克'),
    ('赢火箭'),
    ('战地雷')
    ;
    
    
    #增加学生
    insert into student(name,customer_id) values
    ('李飞机',1),
    ('王大炮',2)
    ;
    复制代码
     其他例子

    七 作业

    练习:账号信息表,用户组,主机表,主机组

    #用户表
    create table user(
    id int not null unique auto_increment,
    username varchar(20) not null,
    password varchar(50) not null,
    primary key(username,password)
    );
    
    insert into user(username,password) values
    ('root','123'),
    ('egon','456'),
    ('alex','alex3714')
    ;
    
    
    #用户组表
    create table usergroup(
    id int primary key auto_increment,
    groupname varchar(20) not null unique
    );
    
    insert into usergroup(groupname) values
    ('IT'),
    ('Sale'),
    ('Finance'),
    ('boss')
    ;
    
    
    #主机表
    create table host(
    id int primary key auto_increment,
    ip char(15) not null unique default '127.0.0.1'
    );
    
    insert into host(ip) values
    ('172.16.45.2'),
    ('172.16.31.10'),
    ('172.16.45.3'),
    ('172.16.31.11'),
    ('172.10.45.3'),
    ('172.10.45.4'),
    ('172.10.45.5'),
    ('192.168.1.20'),
    ('192.168.1.21'),
    ('192.168.1.22'),
    ('192.168.2.23'),
    ('192.168.2.223'),
    ('192.168.2.24'),
    ('192.168.3.22'),
    ('192.168.3.23'),
    ('192.168.3.24')
    ;
    
    
    #业务线表
    create table business(
    id int primary key auto_increment,
    business varchar(20) not null unique
    );
    insert into business(business) values
    ('轻松贷'),
    ('随便花'),
    ('大富翁'),
    ('穷一生')
    ;
    
    
    #建关系:user与usergroup
    
    create table user2usergroup(
    id int not null unique auto_increment,
    user_id int not null,
    group_id int not null,
    primary key(user_id,group_id),
    foreign key(user_id) references user(id),
    foreign key(group_id) references usergroup(id)
    );
    
    insert into user2usergroup(user_id,group_id) values
    (1,1),
    (1,2),
    (1,3),
    (1,4),
    (2,3),
    (2,4),
    (3,4)
    ;
    
    
    
    #建关系:host与business
    
    create table host2business(
    id int not null unique auto_increment,
    host_id int not null,
    business_id int not null,
    primary key(host_id,business_id),
    foreign key(host_id) references host(id),
    foreign key(business_id) references business(id)
    );
    
    insert into host2business(host_id,business_id) values
    (1,1),
    (1,2),
    (1,3),
    (2,2),
    (2,3),
    (3,4)
    ;
    
    #建关系:user与host
    
    create table user2host(
    id int not null unique auto_increment,
    user_id int not null,
    host_id int not null,
    primary key(user_id,host_id),
    foreign key(user_id) references user(id),
    foreign key(host_id) references host(id)
    );
    
    insert into user2host(user_id,host_id) values
    (1,1),
    (1,2),
    (1,3),
    (1,4),
    (1,5),
    (1,6),
    (1,7),
    (1,8),
    (1,9),
    (1,10),
    (1,11),
    (1,12),
    (1,13),
    (1,14),
    (1,15),
    (1,16),
    (2,2),
    (2,3),
    (2,4),
    (2,5),
    (3,10),
    (3,11),
    (3,12)
    ;
    View Code

    实例:

    1 not null 与default
    
    create table student2(
    id int primary key auto_increment,
    name char(5),
    sex enum('male','female') not null default 'female'
    );
    
    insert into student2(name) values('alex');
    
    
    create table student3(
    id int primary key auto_increment,
    name char(5),
    age int not null default 30
    );
    
    insert into student3(name) values('alex');
    
    
    2 unique
    #单列唯一
    create table teacher(
    id int not null unique,
    name char(10)
    );
    insert into teacher values(1,'egon');
    insert into teacher values(1,'alex');
    
    #多列唯一
    #255.255.255.255
    create table services(
    id int primary key auto_increment,
    name char(10),
    host char(15),
    port int,
    constraint host_port unique(host,port)
    );
    
    insert into services values('ftp','192.168.20.17',8080);
    insert into services values('httpd','192.168.20.17',8081);
    
    
    
    
    #auto_increment_offset:偏移量
    create table dep(
    id int primary key auto_increment,
    name char(10)
    );
    insert into dep(name) values('IT'),('HR'),('SALE'),('Boss');
    
    create table dep1(
    id int primary key auto_increment,
    name char(10)
    )auto_increment=10;(指定从10开始自增)
    insert into dep1(name) values('IT'),('HR'),('SALE'),('Boss');
    
    
    auto_increment_increment:步长
    create table dep2(
    id int primary key auto_increment,
    name char(10)
    );
    set session auto_increment_increment=2; #会话级,只对当前会话有效
    set global auto_increment_increment=2; #全局,对所有的会话都有效
    insert into dep1(name) values('IT'),('HR'),('SALE'),('Boss');
    
    
    #auto_increment_offset:偏移量+auto_increment_increment:步长
    注意:如果auto_increment_offset的值大于auto_increment_increment的值,则auto_increment_offset的值会被忽略
    set session auto_increment_offset=2;
    set session auto_increment_increment=3;
    show variables like '%auto_in%';(模糊查找)
    
    create table dep3(
    id int primary key auto_increment,
    name char(10)
    );
    insert into dep3(name) values('IT'),('HR'),('SALE'),('Boss');
    
    
    
    #foreign key
    #!!!先建被关联的表,并且被关联的字段必须唯一
    create table dep(
    id int primary key auto_increment,
    name varchar(50),
    comment varchar(100)
    );
    
    create table emp_info(
    id int primary key auto_increment,
    name varchar(20),
    dep_id int,
    constraint fk_depid_id foreign key(dep_id) references dep(id)
    on delete cascade
    on update cascade
    );
    
    #先给被关联的表初始化记录
    insert into dep values
    (1,'欧德博爱技术有限事业部','说的好...'),
    (2,'艾利克斯人力资源部','招不到人'),
    (3,'销售部','卖不出东西');
    
    
    insert into emp_info values
    (1,'egon',1),
    (2,'alex1',2),
    (3,'alex2',2),
    (4,'alex3',2),
    (5,'李坦克',3),
    (6,'刘飞机',3),
    (7,'张火箭',3),
    (8,'林子弹',3),
    (9,'加特林',3)
    ;

    五 修改表ALTER TABLE

    复制代码
    语法:
    1. 修改表名
          ALTER TABLE 表名 
                              RENAME 新表名;
    
    2. 增加字段
          ALTER TABLE 表名
                              ADD 字段名  数据类型 [完整性约束条件…],
                            ADD 字段名  数据类型 [完整性约束条件…];
        ALTER TABLE 表名
                              ADD 字段名  数据类型 [完整性约束条件…]  FIRST;
        ALTER TABLE 表名
                                ADD 字段名  数据类型 [完整性约束条件…]  AFTER 字段名;
                                
    3. 删除字段
          ALTER TABLE 表名 
                                        DROP 字段名;
    
    4. 修改字段
          ALTER TABLE 表名 
                              MODIFY  字段名 数据类型 [完整性约束条件…];
          ALTER TABLE 表名 
                              CHANGE 旧字段名 新字段名 旧数据类型 [完整性约束条件…];
          ALTER TABLE 表名 
                              CHANGE 旧字段名 新字段名 新数据类型 [完整性约束条件…];
    
    示例:
    1. 修改存储引擎
    mysql> alter table service 
        -> engine=innodb;
    
    2. 添加字段
    mysql> alter table student10
        -> add name varchar(20) not null,
        -> add age int(3) not null default 22;
        
    mysql> alter table student10
        -> add stu_num varchar(10) not null after name;                //添加name字段之后
    
    mysql> alter table student10                        
        -> add sex enum('male','female') default 'male' first;          //添加到最前面
    
    3. 删除字段
    mysql> alter table student10
        -> drop sex;
    
    mysql> alter table service
        -> drop mac;
    
    4. 修改字段类型modify
    mysql> alter table student10
        -> modify age int(3);
    mysql> alter table student10
        -> modify id int(11) not null primary key auto_increment;    //修改为主键
    
    5. 增加约束(针对已有的主键增加auto_increment)
    mysql> alter table student10 modify id int(11) not null primary key auto_increment;
    ERROR 1068 (42000): Multiple primary key defined
    
    mysql> alter table student10 modify id int(11) not null auto_increment;
    Query OK, 0 rows affected (0.01 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    6. 对已经存在的表增加复合主键
    mysql> alter table service2
        -> add primary key(host_ip,port);        
    
    7. 增加主键
    mysql> alter table student1
        -> modify name varchar(10) not null primary key;
    
    8. 增加主键和自动增长
    mysql> alter table student1
        -> modify id int not null primary key auto_increment;
    
    9. 删除主键
    a. 删除自增约束
    mysql> alter table student10 modify id int(11) not null; 
    
    b. 删除主键
    mysql> alter table student10                                 
        -> drop primary key;
    复制代码

    六 复制表

    复制代码
    复制表结构+记录 (key不会复制: 主键、外键和索引)
    mysql> create table new_service select * from service;
    
    只复制表结构
    mysql> select * from service where 1=2;        //条件为假,查不到任何记录
    Empty set (0.00 sec)
    mysql> create table new1_service select * from service where 1=2;  
    Query OK, 0 rows affected (0.00 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    mysql> create table t4 like employees;
    复制代码

    七 删除表

    DROP TABLE 表名;

    mysql五:数据操作

     

    一 介绍

    MySQL数据操作: DML

    ========================================================

    在MySQL管理软件中,可以通过SQL语句中的DML语言来实现数据的操作,包括

    1. 使用INSERT实现数据的插入
    2. UPDATE实现数据的更新
    3. 使用DELETE实现数据的删除
    4. 使用SELECT查询数据以及。

    ========================================================

    本节内容包括:

    插入数据
    更新数据
    删除数据
    查询数据

    二 插入数据INSERT

    复制代码
    1. 插入完整数据(顺序插入)
        语法一:
        INSERT INTO 表名(字段1,字段2,字段3…字段n) VALUES(值1,值2,值3…值n);
    
        语法二:
        INSERT INTO 表名 VALUES (值1,值2,值3…值n);
    
    2. 指定字段插入数据
        语法:
        INSERT INTO 表名(字段1,字段2,字段3…) VALUES (值1,值2,值3…);
    
    3. 插入多条记录
        语法:
        INSERT INTO 表名 VALUES
            (值1,值2,值3…值n),
            (值1,值2,值3…值n),
            (值1,值2,值3…值n);
            
    4. 插入查询结果
        语法:
        INSERT INTO 表名(字段1,字段2,字段3…字段n) 
                        SELECT (字段1,字段2,字段3…字段n) FROM 表2
                        WHERE …;
    复制代码

    三 更新数据UPDATE

    复制代码
    语法:
        UPDATE 表名 SET
            字段1=值1,
            字段2=值2,
            WHERE CONDITION;
    
    示例:
        UPDATE mysql.user SET password=password(‘123’) 
            where user=’root’ and host=’localhost’;
    复制代码

    四 删除数据DELETE

    复制代码
    语法:
        DELETE FROM 表名 
            WHERE CONITION;
    
    示例:
        DELETE FROM mysql.user 
            WHERE password=’’;
    
    练习:
        更新MySQL root用户密码为mysql123
        删除除从本地登录的root用户以外的所有用户
    复制代码

    五 查询数据SELECT

    mysql五-1:单表查询

     

    一 介绍

    本节内容:

    查询语法

    关键字的执行优先级

    简单查询

    单条件查询:WHERE

    分组查询:GROUP BY

    HAVING

    查询排序:ORDER BY

    限制查询的记录数:LIMIT

    使用聚合函数查询

    使用正则表达式查询

    复制代码
    company.employee
        员工id      id                  int             
        姓名        emp_name            varchar
        性别        sex                 enum
        年龄        age                 int
        入职日期     hire_date           date
        岗位        post                varchar
        职位描述     post_comment        varchar
        薪水        salary              double
        办公室       office              int
        部门编号     depart_id           int
    
    
    
    #创建表
    create table employee(
    id int not null unique auto_increment,
    name varchar(20) not null,
    sex enum('male','female') not null default 'male', #大部分是男的
    age int(3) unsigned not null default 28,
    hire_date date not null,
    post varchar(50),
    post_comment varchar(100),
    salary double(15,2),
    office int, #一个部门一个屋子
    depart_id int
    );
    
    
    #查看表结构
    mysql> desc employee;
    +--------------+-----------------------+------+-----+---------+----------------+
    | Field        | Type                  | Null | Key | Default | Extra          |
    +--------------+-----------------------+------+-----+---------+----------------+
    | id           | int(11)               | NO   | PRI | NULL    | auto_increment |
    | name         | varchar(20)           | NO   |     | NULL    |                |
    | sex          | enum('male','female') | NO   |     | male    |                |
    | age          | int(3) unsigned       | NO   |     | 28      |                |
    | hire_date    | date                  | NO   |     | NULL    |                |
    | post         | varchar(50)           | YES  |     | NULL    |                |
    | post_comment | varchar(100)          | YES  |     | NULL    |                |
    | salary       | double(15,2)          | YES  |     | NULL    |                |
    | office       | int(11)               | YES  |     | NULL    |                |
    | depart_id    | int(11)               | YES  |     | NULL    |                |
    +--------------+-----------------------+------+-----+---------+----------------+
    
    #插入记录
    #三个部门:教学,销售,运营
    insert into employee(name,sex,age,hire_date,post,salary,office,depart_id) values
    ('egon','male',18,'20170301','老男孩驻沙河办事处外交大使',7300.33,401,1), #以下是教学部
    ('alex','male',78,'20150302','teacher',1000000.31,401,1),
    ('wupeiqi','male',81,'20130305','teacher',8300,401,1),
    ('yuanhao','male',73,'20140701','teacher',3500,401,1),
    ('liwenzhou','male',28,'20121101','teacher',2100,401,1),
    ('jingliyang','female',18,'20110211','teacher',9000,401,1),
    ('jinxin','male',18,'19000301','teacher',30000,401,1),
    ('成龙','male',48,'20101111','teacher',10000,401,1),
    
    ('歪歪','female',48,'20150311','sale',3000.13,402,2),#以下是销售部门
    ('丫丫','female',38,'20101101','sale',2000.35,402,2),
    ('丁丁','female',18,'20110312','sale',1000.37,402,2),
    ('星星','female',18,'20160513','sale',3000.29,402,2),
    ('格格','female',28,'20170127','sale',4000.33,402,2),
    
    ('张野','male',28,'20160311','operation',10000.13,403,3), #以下是运营部门
    ('程咬金','male',18,'19970312','operation',20000,403,3),
    ('程咬银','female',18,'20130311','operation',19000,403,3),
    ('程咬铜','male',18,'20150411','operation',18000,403,3),
    ('程咬铁','female',18,'20140512','operation',17000,403,3)
    ;
    复制代码

    二 查询语法

    SELECT 字段1,字段2... FROM 表名
                      WHERE 条件
                      GROUP BY field
                      HAVING 筛选
                      ORDER BY field
                      LIMIT 限制条数

    三 关键字的执行优先级(重点)

    复制代码
    重点中的重点:关键字的执行优先级
    from
    where
    group by
    having
    select
    distinct
    order by
    limit
    复制代码

    1.找到表:from

    2.拿着where指定的约束条件,去文件/表中取出一条条记录

    3.将取出的一条条记录进行分组group by,如果没有group by,则整体作为一组

    4.如果有聚合函数,则将组进行聚合

    5.将4的结果过滤:having

    6.查出结果:select

    7.去重

    8.将6的结果按条件排序:order by

    9.将7的结果限制显示条数

    详细见:http://www.cnblogs.com/linhaifeng/articles/7372774.html

    四 简单查询

    复制代码
    #简单查询
        SELECT id,name,sex,age,hire_date,post,post_comment,salary,office,depart_id 
        FROM employee;
    
        SELECT * FROM employee;
    
        SELECT name,salary FROM employee;
    
    #避免重复DISTINCT
        SELECT DISTINCT post FROM employee;    
    
    #通过四则运算查询
        SELECT name, salary*12 FROM employee;
        SELECT name, salary*12 AS Annual_salary FROM employee;
        SELECT name, salary*12 Annual_salary FROM employee;
    
    #定义显示格式
       CONCAT() 函数用于连接字符串
       SELECT CONCAT('姓名: ',name,'  年薪: ', salary*12)  AS Annual_salary 
       FROM employee;
       
       CONCAT_WS() 第一个参数为分隔符
       SELECT CONCAT_WS(':',name,salary*12)  AS Annual_salary 
       FROM employee;
    复制代码

    小练习:

    1 查出所有员工的名字,薪资,格式为
        <名字:egon>    <薪资:3000>
    2 查出所有的岗位(去掉重复)
    3 查出所有员工名字,以及他们的年薪,年薪的字段名为annual_year
     View Code 

    五 WHERE约束

    强调:where是一种约束条件,mysql会拿着where指定的条件去表中取数据,而having则是在取出数据后进行过滤

    where字句中可以使用:

    1. 比较运算符:> < >= <= <> !=
    2. between 80 and 100 值在10到20之间
    3. in(80,90,100) 值是10或20或30
    4. like 'egon%'
        pattern可以是%或_,
        %表示任意多字符
        _表示一个字符 
    5. 逻辑运算符:在多个条件直接可以使用逻辑运算符 and or not

    复制代码
    #1:单条件查询
        SELECT name FROM employee
            WHERE post='sale';
            
    #2:多条件查询
        SELECT name,salary FROM employee
            WHERE post='teacher' AND salary>10000;
    
    #3:关键字BETWEEN AND
        SELECT name,salary FROM employee 
            WHERE salary BETWEEN 10000 AND 20000;
    
        SELECT name,salary FROM employee 
            WHERE salary NOT BETWEEN 10000 AND 20000;
        
    #4:关键字IS NULL(判断某个字段是否为NULL不能用等号,需要用IS)
        SELECT name,post_comment FROM employee 
            WHERE post_comment IS NULL;
    
        SELECT name,post_comment FROM employee 
            WHERE post_comment IS NOT NULL;
            
        SELECT name,post_comment FROM employee 
            WHERE post_comment=''; 注意''是空字符串,不是null
        ps:
            执行
            update employee set post_comment='' where id=2;
            再用上条查看,就会有结果了
    
    #5:关键字IN集合查询
        SELECT name,salary FROM employee 
            WHERE salary=3000 OR salary=3500 OR salary=4000 OR salary=9000 ;
        
        SELECT name,salary FROM employee 
            WHERE salary IN (3000,3500,4000,9000) ;
    
        SELECT name,salary FROM employee 
            WHERE salary NOT IN (3000,3500,4000,9000) ;
    
    #6:关键字LIKE模糊查询
        通配符’%’
        SELECT * FROM employee 
                WHERE name LIKE 'eg%';
    
        通配符’_’
        SELECT * FROM employee 
                WHERE name LIKE 'al__';
    复制代码

    小练习:

    复制代码
    1. 查看岗位是teacher的员工姓名、年龄
    2. 查看岗位是teacher且年龄大于30岁的员工姓名、年龄
    3. 查看岗位是teacher且薪资在9000-1000范围内的员工姓名、年龄、薪资
    4. 查看岗位描述不为NULL的员工信息
    5. 查看岗位是teacher且薪资是10000或9000或30000的员工姓名、年龄、薪资
    6. 查看岗位是teacher且薪资不是10000或9000或30000的员工姓名、年龄、薪资
    7. 查看岗位是teacher且名字是jin开头的员工姓名、年薪
    复制代码
    复制代码
    select name,age from employee where post = 'teacher';
    select name,age from employee where post='teacher' and age > 30; 
    select name,age,salary from employee where post='teacher' and salary between 9000 and 10000;
    select * from employee where post_comment is not null;
    select name,age,salary from employee where post='teacher' and salary in (10000,9000,30000);
    select name,age,salary from employee where post='teacher' and salary not in (10000,9000,30000);
    select name,salary*12 from employee where post='teacher' and name like 'jin%';
    复制代码
     

    六 分组查询:GROUP BY

    大前提:可以按照任意字段分组,但分完组后,只能查看分组的那个字段,要想取的组内的其他字段信息,需要借助函数

    复制代码
    单独使用GROUP BY关键字分组
        SELECT post FROM employee GROUP BY post;
        注意:我们按照post字段分组,那么select查询的字段只能是post,想要获取组内的其他相关信息,需要借助函数
    
    GROUP BY关键字和GROUP_CONCAT()函数一起使用
        SELECT post,GROUP_CONCAT(name) FROM employee GROUP BY post;#按照岗位分组,并查看组内成员名
        SELECT post,GROUP_CONCAT(name) as emp_members FROM employee GROUP BY post;
    
    GROUP BY与聚合函数一起使用
        select post,count(id) as count from employee group by post;#按照岗位分组,并查看每个组有多少人
    复制代码

    强调:

    如果我们用unique的字段作为分组的依据,则每一条记录自成一组,这种分组没有意义
    多条记录之间的某个字段值相同,该字段通常用来作为分组的依据
     !!!MySQL 5.7默认ONLY_FULL_GROUP_BY语义介绍 

    小练习:

    复制代码
    1. 查询岗位名以及岗位包含的所有员工名字
    2. 查询岗位名以及各岗位内包含的员工个数
    3. 查询公司内男员工和女员工的个数
    4. 查询岗位名以及各岗位的平均薪资
    5. 查询岗位名以及各岗位的最高薪资
    6. 查询岗位名以及各岗位的最低薪资
    7. 查询男员工与男员工的平均薪资,女员工与女员工的平均薪资
    复制代码
    复制代码
    #题1:分组
    mysql> select post,group_concat(name) from employee group by post;
    +-----------------------------------------+---------------------------------------------------------+
    | post                                    | group_concat(name)                                      |
    +-----------------------------------------+---------------------------------------------------------+
    | operation                               | 张野,程咬金,程咬银,程咬铜,程咬铁                        |
    | sale                                    | 歪歪,丫丫,丁丁,星星,格格                                |
    | teacher                                 | alex,wupeiqi,yuanhao,liwenzhou,jingliyang,jinxin,成龙   |
    | 老男孩驻沙河办事处外交大使              | egon                                                    |
    +-----------------------------------------+---------------------------------------------------------+
    
    
    #题目2:
    mysql> select post,count(id) from employee group by post;
    +-----------------------------------------+-----------+
    | post                                    | count(id) |
    +-----------------------------------------+-----------+
    | operation                               |         5 |
    | sale                                    |         5 |
    | teacher                                 |         7 |
    | 老男孩驻沙河办事处外交大使              |         1 |
    +-----------------------------------------+-----------+
    
    
    #题目3:
    mysql> select sex,count(id) from employee group by sex;
    +--------+-----------+
    | sex    | count(id) |
    +--------+-----------+
    | male   |        10 |
    | female |         8 |
    +--------+-----------+
    
    #题目4:
    mysql> select post,avg(salary) from employee group by post;
    +-----------------------------------------+---------------+
    | post                                    | avg(salary)   |
    +-----------------------------------------+---------------+
    | operation                               |  16800.026000 |
    | sale                                    |   2600.294000 |
    | teacher                                 | 151842.901429 |
    | 老男孩驻沙河办事处外交大使              |   7300.330000 |
    +-----------------------------------------+---------------+
    
    #题目5
    mysql> select post,max(salary) from employee group by post;
    +-----------------------------------------+-------------+
    | post                                    | max(salary) |
    +-----------------------------------------+-------------+
    | operation                               |    20000.00 |
    | sale                                    |     4000.33 |
    | teacher                                 |  1000000.31 |
    | 老男孩驻沙河办事处外交大使              |     7300.33 |
    +-----------------------------------------+-------------+
    
    #题目6
    mysql> select post,min(salary) from employee group by post;
    +-----------------------------------------+-------------+
    | post                                    | min(salary) |
    +-----------------------------------------+-------------+
    | operation                               |    10000.13 |
    | sale                                    |     1000.37 |
    | teacher                                 |     2100.00 |
    | 老男孩驻沙河办事处外交大使              |     7300.33 |
    +-----------------------------------------+-------------+
    
    #题目七
    mysql> select sex,avg(salary) from employee group by sex;
    +--------+---------------+
    | sex    | avg(salary)   |
    +--------+---------------+
    | male   | 110920.077000 |
    | female |   7250.183750 |
    +--------+---------------+
    复制代码

    七 使用聚合函数查询

    先from找到表

    再用where的条件约束去表中取出记录

    然后进行分组group by,没有分组则默认一组

    然后进行聚合

    最后select出结果

    复制代码
    示例:
        SELECT COUNT(*) FROM employee;
        SELECT COUNT(*) FROM employee WHERE depart_id=1;
        SELECT MAX(salary) FROM employee;
        SELECT MIN(salary) FROM employee;
        SELECT AVG(salary) FROM employee;
        SELECT SUM(salary) FROM employee;
        SELECT SUM(salary) FROM employee WHERE depart_id=3;
    复制代码

    八 HAVING过滤

    HAVING与WHERE在语法上是一样的

    select * from employee where salary > 10000;
    select * from employee having salary > 10000;

    HAVING与WHERE不一样的地方在于!!!!!!

    复制代码
    #!!!执行优先级从高到低:where > group by > 聚合函数 > having 
    #1. Where 是一个约束声明,使用Where约束来自数据库的数据,Where是在结果返回之前起作用的(先找到表,按照where的约束条件,从表(文件)中取出数据),Where中不能使用聚合函数。
    
    #2. Having是一个过滤声明,是在查询返回结果集以后对查询结果进行的过滤操作(先找到表,按照where的约束条件,从表(文件)中取出数据,然后group by分组,如果没有group by则所有记录整体为一组,然后执行聚合函数,然后使用having对聚合的结果进行过滤),在Having中可以使用聚合函数。
    
    #3. having可以放到group by之后,而where只能放到group by之前
    
    #4. 在查询过程中聚合语句(sum,min,max,avg,count)要比having子句优先执行。而where子句在查询过程中执行优先级高于聚合语句。
    复制代码

    验证不同之处

    复制代码
    #验证之前再次强调:执行优先级从高到低:where > group by > 聚合函数 > having 
    select count(id) from employee where salary > 10000; #正确,分析:where先执行,后执行聚合count(id),然后select出结果
    select count(id) from employee having salary > 10000;#错误,分析:先执行聚合count(id),后执行having过滤,无法对id进行salary>10000的过滤
    
    #以上两条sql的顺序是
    1:找到表employee--->用where过滤---->没有分组则默认一组执行聚合count(id)--->select执行查看组内id数目
    2:找到表employee--->没有分组则默认一组执行聚合count(id)---->having 基于上一步聚合的结果(此时只有count(id)字段了)进行salary>10000的过滤,很明显,根本无法获取到salary字段
    复制代码

    其他需要注意的问题

    select post,group_concat(name) from employee group by post having salary > 10000;#错误,分组后无法直接取到salary字段
    select post,group_concat(name) from employee group by post having avg(salary) > 10000;

    小练习:

    1. 查询各岗位内包含的员工个数小于2的岗位名、岗位内包含员工名字、个数
    3. 查询各岗位平均薪资大于10000的岗位名、平均工资
    4. 查询各岗位平均薪资大于10000且小于20000的岗位名、平均工资
    复制代码
    #题1:
    mysql> select post,group_concat(name),count(id) from employee group by post having count(id) < 2;
    +-----------------------------------------+--------------------+-----------+
    | post                                    | group_concat(name) | count(id) |
    +-----------------------------------------+--------------------+-----------+
    | 老男孩驻沙河办事处外交大使              | egon               |         1 |
    +-----------------------------------------+--------------------+-----------+
    
    #题目2:
    mysql> select post,avg(salary) from employee group by post having avg(salary) > 10000;
    +-----------+---------------+
    | post      | avg(salary)   |
    +-----------+---------------+
    | operation |  16800.026000 |
    | teacher   | 151842.901429 |
    +-----------+---------------+
    
    #题目3:
    mysql> select post,avg(salary) from employee group by post having avg(salary) > 10000 and avg(salary) <20000;
    +-----------+--------------+
    | post      | avg(salary)  |
    +-----------+--------------+
    | operation | 16800.026000 |
    +-----------+--------------+
    复制代码
     

    九 查询排序:ORDER BY

    复制代码
    按单列排序
        SELECT * FROM employee ORDER BY salary;
        SELECT * FROM employee ORDER BY salary ASC;
        SELECT * FROM employee ORDER BY salary DESC;
    
    按多列排序:先按照age排序,如果年纪相同,则按照薪资排序
        SELECT * from employee
            ORDER BY age,
            salary DESC;
    复制代码

    小练习:

    1. 查询所有员工信息,先按照age升序排序,如果age相同则按照hire_date降序排序
    2. 查询各岗位平均薪资大于10000的岗位名、平均工资,结果按平均薪资升序排列
    3. 查询各岗位平均薪资大于10000的岗位名、平均工资,结果按平均薪资降序排列
    复制代码
    #题目1
    mysql> select * from employee ORDER BY age asc,hire_date desc;
    
    #题目2
    mysql> select post,avg(salary) from employee group by post having avg(salary) > 10000 order by avg(salary) asc;
    +-----------+---------------+
    | post      | avg(salary)   |
    +-----------+---------------+
    | operation |  16800.026000 |
    | teacher   | 151842.901429 |
    +-----------+---------------+
    
    #题目3
    mysql> select post,avg(salary) from employee group by post having avg(salary) > 10000 order by avg(salary) desc;
    +-----------+---------------+
    | post      | avg(salary)   |
    +-----------+---------------+
    | teacher   | 151842.901429 |
    | operation |  16800.026000 |
    +-----------+---------------+
    复制代码

    十 限制查询的记录数:LIMIT

    复制代码
    示例:
        SELECT * FROM employee ORDER BY salary DESC 
            LIMIT 3;                    #默认初始位置为0 
        
        SELECT * FROM employee ORDER BY salary DESC
            LIMIT 0,5; #从第0开始,即先查询出第一条,然后包含这一条在内往后查5条
    
        SELECT * FROM employee ORDER BY salary DESC
            LIMIT 5,5; #从第5开始,即先查询出第6条,然后包含这一条在内往后查5条
    复制代码

    小练习:

    1. 分页显示,每页5条
    复制代码
    mysql> select * from  employee limit 0,5;
    +----+-----------+------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
    | id | name      | sex  | age | hire_date  | post                                    | post_comment | salary     | office | depart_id |
    +----+-----------+------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
    |  1 | egon      | male |  18 | 2017-03-01 | 老男孩驻沙河办事处外交大使              | NULL         |    7300.33 |    401 |         1 |
    |  2 | alex      | male |  78 | 2015-03-02 | teacher                                 |              | 1000000.31 |    401 |         1 |
    |  3 | wupeiqi   | male |  81 | 2013-03-05 | teacher                                 | NULL         |    8300.00 |    401 |         1 |
    |  4 | yuanhao   | male |  73 | 2014-07-01 | teacher                                 | NULL         |    3500.00 |    401 |         1 |
    |  5 | liwenzhou | male |  28 | 2012-11-01 | teacher                                 | NULL         |    2100.00 |    401 |         1 |
    +----+-----------+------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
    5 rows in set (0.00 sec)
    
    mysql> select * from  employee limit 5,5;
    +----+------------+--------+-----+------------+---------+--------------+----------+--------+-----------+
    | id | name       | sex    | age | hire_date  | post    | post_comment | salary   | office | depart_id |
    +----+------------+--------+-----+------------+---------+--------------+----------+--------+-----------+
    |  6 | jingliyang | female |  18 | 2011-02-11 | teacher | NULL         |  9000.00 |    401 |         1 |
    |  7 | jinxin     | male   |  18 | 1900-03-01 | teacher | NULL         | 30000.00 |    401 |         1 |
    |  8 | 成龙       | male   |  48 | 2010-11-11 | teacher | NULL         | 10000.00 |    401 |         1 |
    |  9 | 歪歪       | female |  48 | 2015-03-11 | sale    | NULL         |  3000.13 |    402 |         2 |
    | 10 | 丫丫       | female |  38 | 2010-11-01 | sale    | NULL         |  2000.35 |    402 |         2 |
    +----+------------+--------+-----+------------+---------+--------------+----------+--------+-----------+
    5 rows in set (0.00 sec)
    
    mysql> select * from  employee limit 10,5;
    +----+-----------+--------+-----+------------+-----------+--------------+----------+--------+-----------+
    | id | name      | sex    | age | hire_date  | post      | post_comment | salary   | office | depart_id |
    +----+-----------+--------+-----+------------+-----------+--------------+----------+--------+-----------+
    | 11 | 丁丁      | female |  18 | 2011-03-12 | sale      | NULL         |  1000.37 |    402 |         2 |
    | 12 | 星星      | female |  18 | 2016-05-13 | sale      | NULL         |  3000.29 |    402 |         2 |
    | 13 | 格格      | female |  28 | 2017-01-27 | sale      | NULL         |  4000.33 |    402 |         2 |
    | 14 | 张野      | male   |  28 | 2016-03-11 | operation | NULL         | 10000.13 |    403 |         3 |
    | 15 | 程咬金    | male   |  18 | 1997-03-12 | operation | NULL         | 20000.00 |    403 |         3 |
    +----+-----------+--------+-----+------------+-----------+--------------+----------+--------+-----------+
    5 rows in set (0.00 sec)
    复制代码
     

    十一 使用正则表达式查询

    复制代码
    SELECT * FROM employee WHERE name REGEXP '^ale';
    
    SELECT * FROM employee WHERE name REGEXP 'on$';
    
    SELECT * FROM employee WHERE name REGEXP 'm{2}';
    
    
    小结:对字符串匹配的方式
    WHERE name = 'egon';
    WHERE name LIKE 'yua%';
    WHERE name REGEXP 'on$';
    复制代码

    小练习:

    查看所有员工中名字是jin开头,n或者g结果的员工信息
    select * from employee where name regexp '^jin.*[gn]$';

     实例:

    1 简单查询
    select * from employee;
    select name,salary from employee;
    
    2 where条件
    select name,salary from employee where salary > 10000;
    select name,salary from employee where salary > 10000 and salary < 20000;
    select name,salary from employee where salary between 10000 and 20000;
    select name,salary from employee where salary not between 10000 and 20000;
    
    select name,salary from employee where salary = 10000 or salary = 20000 or salary = 30000;
    select name,salary from employee where salary in (10000,20000,30000);
    
    
    select * from employee where salary = 10000 or age = 18 or sex='male';
    
    select * from employee where post_comment is Null;
    select * from employee where post_comment = Null;
    select * from employee where post_comment is not Null;
    
     select * from employee where name like '%n%';
    
    select * from employee where name like 'e__n';
    
    3 group by分组
    mysql> select depart_id,group_concat(name)  from employee group by depart_id;
    +-----------+--------------------------------------------------------------+
    | depart_id | group_concat(name)                                           |
    +-----------+--------------------------------------------------------------+
    |         1 | egon,alex,wupeiqi,yuanhao,liwenzhou,jingliyang,jinxin,成龙   |
    |         2 | 歪歪,丫丫,丁丁,星星,格格                                     |
    |         3 | 张野,程咬金,程咬银,程咬铜,程咬铁                             |
    +-----------+--------------------------------------------------------------+
    3 rows in set (0.00 sec)
    
    mysql> select depart_id,count(id)  from employee group by depart_id;
    +-----------+-----------+
    | depart_id | count(id) |
    +-----------+-----------+
    |         1 |         8 |
    |         2 |         5 |
    |         3 |         5 |
    +-----------+-----------+
    3 rows in set (0.01 sec)
    
    mysql> select depart_id,group_concat(id)  from employee group by depart_id;
    +-----------+------------------+
    | depart_id | group_concat(id) |
    +-----------+------------------+
    |         1 | 1,2,3,4,5,6,7,8  |
    |         2 | 9,10,11,12,13    |
    |         3 | 14,15,16,17,18   |
    +-----------+------------------+
    3 rows in set (0.00 sec)
    
    mysql> select depart_id,count(id)  from employee group by depart_id;
    +-----------+-----------+
    | depart_id | count(id) |
    +-----------+-----------+
    |         1 |         8 |
    |         2 |         5 |
    |         3 |         5 |
    +-----------+-----------+
    3 rows in set (0.00 sec)
    
    mysql> select depart_id,max(salary) from employee group by depart_id;
    +-----------+-------------+
    | depart_id | max(salary) |
    +-----------+-------------+
    |         1 |  1000000.31 |
    |         2 |     4000.33 |
    |         3 |    20000.00 |
    +-----------+-------------+
    3 rows in set (0.00 sec)
    
    mysql> select depart_id,min(salary) from employee group by depart_id;
    +-----------+-------------+
    | depart_id | min(salary) |
    +-----------+-------------+
    |         1 |     2100.00 |
    |         2 |     1000.37 |
    |         3 |    10000.13 |
    +-----------+-------------+
    3 rows in set (0.00 sec)
    
    mysql> select depart_id,sum(salary) from employee group by depart_id;
    +-----------+-------------+
    | depart_id | sum(salary) |
    +-----------+-------------+
    |         1 |  1070200.64 |
    |         2 |    13001.47 |
    |         3 |    84000.13 |
    +-----------+-------------+
    3 rows in set (0.00 sec)
    
    mysql> select depart_id,avg(salary) from employee group by depart_id;
    +-----------+---------------+
    | depart_id | avg(salary)   |
    +-----------+---------------+
    |         1 | 133775.080000 |
    |         2 |   2600.294000 |
    |         3 |  16800.026000 |
    +-----------+---------------+
    3 rows in set (0.00 sec)

    mysql五-2:多表查询

     

    一 介绍

    本节主题

    多表连接查询

    复合条件连接查询

    子查询

    准备表

    company.employee
    company.department

    复制代码
    #建表
    create table department(
    id int,
    name varchar(20) 
    );
    
    create table employee(
    id int primary key auto_increment,
    name varchar(20),
    sex enum('male','female') not null default 'male',
    age int,
    dep_id int
    );
    
    #插入数据
    insert into department values
    (200,'技术'),
    (201,'人力资源'),
    (202,'销售'),
    (203,'运营');
    
    insert into employee(name,sex,age,dep_id) values
    ('egon','male',18,200),
    ('alex','female',48,201),
    ('wupeiqi','male',38,201),
    ('yuanhao','female',28,202),
    ('liwenzhou','male',18,200),
    ('jingliyang','female',18,204)
    ;
    
    
    #查看表结构和数据
    mysql> desc department;
    +-------+-------------+------+-----+---------+-------+
    | Field | Type | Null | Key | Default | Extra |
    +-------+-------------+------+-----+---------+-------+
    | id | int(11) | YES | | NULL | |
    | name | varchar(20) | YES | | NULL | |
    +-------+-------------+------+-----+---------+-------+
    
    mysql> desc employee;
    +--------+-----------------------+------+-----+---------+----------------+
    | Field | Type | Null | Key | Default | Extra |
    +--------+-----------------------+------+-----+---------+----------------+
    | id | int(11) | NO | PRI | NULL | auto_increment |
    | name | varchar(20) | YES | | NULL | |
    | sex | enum('male','female') | NO | | male | |
    | age | int(11) | YES | | NULL | |
    | dep_id | int(11) | YES | | NULL | |
    +--------+-----------------------+------+-----+---------+----------------+
    
    mysql> select * from department;
    +------+--------------+
    | id | name |
    +------+--------------+
    | 200 | 技术 |
    | 201 | 人力资源 |
    | 202 | 销售 |
    | 203 | 运营 |
    +------+--------------+
    
    mysql> select * from employee;
    +----+------------+--------+------+--------+
    | id | name | sex | age | dep_id |
    +----+------------+--------+------+--------+
    | 1 | egon | male | 18 | 200 |
    | 2 | alex | female | 48 | 201 |
    | 3 | wupeiqi | male | 38 | 201 |
    | 4 | yuanhao | female | 28 | 202 |
    | 5 | liwenzhou | male | 18 | 200 |
    | 6 | jingliyang | female | 18 | 204 |
    +----+------------+--------+------+--------+
    复制代码

    二 多表连接查询

    #重点:外链接语法
    
    SELECT 字段列表
        FROM 表1 INNER|LEFT|RIGHT JOIN 表2
        ON 表1.字段 = 表2.字段;

    1 交叉连接:不适用任何匹配条件。生成笛卡尔积

    复制代码
    mysql> select * from employee,department;
    +----+------------+--------+------+--------+------+--------------+
    | id | name       | sex    | age  | dep_id | id   | name         |
    +----+------------+--------+------+--------+------+--------------+
    |  1 | egon       | male   |   18 |    200 |  200 | 技术         |
    |  1 | egon       | male   |   18 |    200 |  201 | 人力资源     |
    |  1 | egon       | male   |   18 |    200 |  202 | 销售         |
    |  1 | egon       | male   |   18 |    200 |  203 | 运营         |
    |  2 | alex       | female |   48 |    201 |  200 | 技术         |
    |  2 | alex       | female |   48 |    201 |  201 | 人力资源     |
    |  2 | alex       | female |   48 |    201 |  202 | 销售         |
    |  2 | alex       | female |   48 |    201 |  203 | 运营         |
    |  3 | wupeiqi    | male   |   38 |    201 |  200 | 技术         |
    |  3 | wupeiqi    | male   |   38 |    201 |  201 | 人力资源     |
    |  3 | wupeiqi    | male   |   38 |    201 |  202 | 销售         |
    |  3 | wupeiqi    | male   |   38 |    201 |  203 | 运营         |
    |  4 | yuanhao    | female |   28 |    202 |  200 | 技术         |
    |  4 | yuanhao    | female |   28 |    202 |  201 | 人力资源     |
    |  4 | yuanhao    | female |   28 |    202 |  202 | 销售         |
    |  4 | yuanhao    | female |   28 |    202 |  203 | 运营         |
    |  5 | liwenzhou  | male   |   18 |    200 |  200 | 技术         |
    |  5 | liwenzhou  | male   |   18 |    200 |  201 | 人力资源     |
    |  5 | liwenzhou  | male   |   18 |    200 |  202 | 销售         |
    |  5 | liwenzhou  | male   |   18 |    200 |  203 | 运营         |
    |  6 | jingliyang | female |   18 |    204 |  200 | 技术         |
    |  6 | jingliyang | female |   18 |    204 |  201 | 人力资源     |
    |  6 | jingliyang | female |   18 |    204 |  202 | 销售         |
    |  6 | jingliyang | female |   18 |    204 |  203 | 运营         |
    +----+------------+--------+------+--------+------+--------------+
    复制代码

    2 内连接:只连接匹配的行

    复制代码
    #找两张表共有的部分,相当于利用条件从笛卡尔积结果中筛选出了正确的结果
    #department没有204这个部门,因而employee表中关于204这条员工信息没有匹配出来
    mysql> select employee.id,employee.name,employee.age,employee.sex,department.name from employee inner join department on employee.dep_id=department.id; 
    +----+-----------+------+--------+--------------+
    | id | name      | age  | sex    | name         |
    +----+-----------+------+--------+--------------+
    |  1 | egon      |   18 | male   | 技术         |
    |  2 | alex      |   48 | female | 人力资源     |
    |  3 | wupeiqi   |   38 | male   | 人力资源     |
    |  4 | yuanhao   |   28 | female | 销售         |
    |  5 | liwenzhou |   18 | male   | 技术         |
    +----+-----------+------+--------+--------------+
    
    #上述sql等同于
    mysql> select employee.id,employee.name,employee.age,employee.sex,department.name from employee,department where employee.dep_id=department.id;
    复制代码

    3 外链接之左连接:优先显示左表全部记录

    复制代码
    #以左表为准,即找出所有员工信息,当然包括没有部门的员工
    #本质就是:在内连接的基础上增加左边有右边没有的结果
    mysql> select employee.id,employee.name,department.name as depart_name from employee left join department on employee.dep_id=department.id;
    +----+------------+--------------+
    | id | name       | depart_name  |
    +----+------------+--------------+
    |  1 | egon       | 技术         |
    |  5 | liwenzhou  | 技术         |
    |  2 | alex       | 人力资源     |
    |  3 | wupeiqi    | 人力资源     |
    |  4 | yuanhao    | 销售         |
    |  6 | jingliyang | NULL         |
    +----+------------+--------------+
    复制代码

    4 外链接之右连接:优先显示右表全部记录

    复制代码
    #以右表为准,即找出所有部门信息,包括没有员工的部门
    #本质就是:在内连接的基础上增加右边有左边没有的结果
    mysql> select employee.id,employee.name,department.name as depart_name from employee right join department on employee.dep_id=department.id;
    +------+-----------+--------------+
    | id   | name      | depart_name  |
    +------+-----------+--------------+
    |    1 | egon      | 技术         |
    |    2 | alex      | 人力资源     |
    |    3 | wupeiqi   | 人力资源     |
    |    4 | yuanhao   | 销售         |
    |    5 | liwenzhou | 技术         |
    | NULL | NULL      | 运营         |
    +------+-----------+--------------+
    复制代码

    5 全外连接:显示左右两个表全部记录

    复制代码
    全外连接:在内连接的基础上增加左边有右边没有的和右边有左边没有的结果
    #注意:mysql不支持全外连接 full JOIN
    #强调:mysql可以使用此种方式间接实现全外连接
    select * from employee left join department on employee.dep_id = department.id
    union
    select * from employee right join department on employee.dep_id = department.id
    ;
    #查看结果
    +------+------------+--------+------+--------+------+--------------+
    | id   | name       | sex    | age  | dep_id | id   | name         |
    +------+------------+--------+------+--------+------+--------------+
    |    1 | egon       | male   |   18 |    200 |  200 | 技术         |
    |    5 | liwenzhou  | male   |   18 |    200 |  200 | 技术         |
    |    2 | alex       | female |   48 |    201 |  201 | 人力资源     |
    |    3 | wupeiqi    | male   |   38 |    201 |  201 | 人力资源     |
    |    4 | yuanhao    | female |   28 |    202 |  202 | 销售         |
    |    6 | jingliyang | female |   18 |    204 | NULL | NULL         |
    | NULL | NULL       | NULL   | NULL |   NULL |  203 | 运营         |
    +------+------------+--------+------+--------+------+--------------+
    
    #注意 union与union all的区别:union会去掉相同的纪录
    复制代码

    三 符合条件连接查询

    复制代码
    #示例1:以内连接的方式查询employee和department表,并且employee表中的age字段值必须大于25,即找出公司所有部门中年龄大于25岁的员工
    select employee.name,employee.age from employee,department
        where employee.dep_id = department.id
        and age > 25;
    
    #示例2:以内连接的方式查询employee和department表,并且以age字段的升序方式显示
    select employee.id,employee.name,employee.age,department.name from employee,department
        where employee.dep_id = department.id
        and age > 25
        order by age asc;
    复制代码

    四 子查询

    #1:子查询是将一个查询语句嵌套在另一个查询语句中。
    #2:内层查询语句的查询结果,可以为外层查询语句提供查询条件。
    #3:子查询中可以包含:IN、NOT IN、ANY、ALL、EXISTS 和 NOT EXISTS等关键字
    #4:还可以包含比较运算符:= 、 !=、> 、<等

    1 带IN关键字的子查询

    #查询employee表,但dep_id必须在department表中出现过
    select * from employee
        where dep_id in
            (select id from department);

    2 带比较运算符的子查询

    复制代码
    #比较运算符:=、!=、>、>=、<、<=、<>
    #查询平均年龄在25岁以上的部门名
    select id,name from department
        where id in 
            (select dep_id from employee group by dep_id having avg(age) > 25);
    
    #查看技术部员工姓名
    select name from employee
        where dep_id in 
            (select id from department where name='技术');
    
    #查看不足1人的部门名
    select name from department
        where id in 
            (select dep_id from employee group by dep_id having count(id) <=1);
    复制代码

    3 带EXISTS关键字的子查询

    EXISTS关字键字表示存在。在使用EXISTS关键字时,内层查询语句不返回查询的记录。
    而是返回一个真假值。True或False
    当返回True时,外层查询语句将进行查询;当返回值为False时,外层查询语句不进行查询

    复制代码
    #department表中存在dept_id=203,Ture
    mysql> select * from employee
        ->     where exists
        ->         (select id from department where id=200);
    +----+------------+--------+------+--------+
    | id | name       | sex    | age  | dep_id |
    +----+------------+--------+------+--------+
    |  1 | egon       | male   |   18 |    200 |
    |  2 | alex       | female |   48 |    201 |
    |  3 | wupeiqi    | male   |   38 |    201 |
    |  4 | yuanhao    | female |   28 |    202 |
    |  5 | liwenzhou  | male   |   18 |    200 |
    |  6 | jingliyang | female |   18 |    204 |
    +----+------------+--------+------+--------+
    
    #department表中存在dept_id=205,False
    mysql> select * from employee
        ->     where exists
        ->         (select id from department where id=204);
    Empty set (0.00 sec)
    复制代码

    五 综合练习

    init.sql文件内容

    复制代码
    /*
     数据导入:
     Navicat Premium Data Transfer
    
     Source Server         : localhost
     Source Server Type    : MySQL
     Source Server Version : 50624
     Source Host           : localhost
     Source Database       : sqlexam
    
     Target Server Type    : MySQL
     Target Server Version : 50624
     File Encoding         : utf-8
    
     Date: 10/21/2016 06:46:46 AM
    */
    
    SET NAMES utf8;
    SET FOREIGN_KEY_CHECKS = 0;
    
    -- ----------------------------
    --  Table structure for `class`
    -- ----------------------------
    DROP TABLE IF EXISTS `class`;
    CREATE TABLE `class` (
      `cid` int(11) NOT NULL AUTO_INCREMENT,
      `caption` varchar(32) NOT NULL,
      PRIMARY KEY (`cid`)
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    --  Records of `class`
    -- ----------------------------
    BEGIN;
    INSERT INTO `class` VALUES ('1', '三年二班'), ('2', '三年三班'), ('3', '一年二班'), ('4', '二年九班');
    COMMIT;
    
    -- ----------------------------
    --  Table structure for `course`
    -- ----------------------------
    DROP TABLE IF EXISTS `course`;
    CREATE TABLE `course` (
      `cid` int(11) NOT NULL AUTO_INCREMENT,
      `cname` varchar(32) NOT NULL,
      `teacher_id` int(11) NOT NULL,
      PRIMARY KEY (`cid`),
      KEY `fk_course_teacher` (`teacher_id`),
      CONSTRAINT `fk_course_teacher` FOREIGN KEY (`teacher_id`) REFERENCES `teacher` (`tid`)
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    --  Records of `course`
    -- ----------------------------
    BEGIN;
    INSERT INTO `course` VALUES ('1', '生物', '1'), ('2', '物理', '2'), ('3', '体育', '3'), ('4', '美术', '2');
    COMMIT;
    
    -- ----------------------------
    --  Table structure for `score`
    -- ----------------------------
    DROP TABLE IF EXISTS `score`;
    CREATE TABLE `score` (
      `sid` int(11) NOT NULL AUTO_INCREMENT,
      `student_id` int(11) NOT NULL,
      `course_id` int(11) NOT NULL,
      `num` int(11) NOT NULL,
      PRIMARY KEY (`sid`),
      KEY `fk_score_student` (`student_id`),
      KEY `fk_score_course` (`course_id`),
      CONSTRAINT `fk_score_course` FOREIGN KEY (`course_id`) REFERENCES `course` (`cid`),
      CONSTRAINT `fk_score_student` FOREIGN KEY (`student_id`) REFERENCES `student` (`sid`)
    ) ENGINE=InnoDB AUTO_INCREMENT=53 DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    --  Records of `score`
    -- ----------------------------
    BEGIN;
    INSERT INTO `score` VALUES ('1', '1', '1', '10'), ('2', '1', '2', '9'), ('5', '1', '4', '66'), ('6', '2', '1', '8'), ('8', '2', '3', '68'), ('9', '2', '4', '99'), ('10', '3', '1', '77'), ('11', '3', '2', '66'), ('12', '3', '3', '87'), ('13', '3', '4', '99'), ('14', '4', '1', '79'), ('15', '4', '2', '11'), ('16', '4', '3', '67'), ('17', '4', '4', '100'), ('18', '5', '1', '79'), ('19', '5', '2', '11'), ('20', '5', '3', '67'), ('21', '5', '4', '100'), ('22', '6', '1', '9'), ('23', '6', '2', '100'), ('24', '6', '3', '67'), ('25', '6', '4', '100'), ('26', '7', '1', '9'), ('27', '7', '2', '100'), ('28', '7', '3', '67'), ('29', '7', '4', '88'), ('30', '8', '1', '9'), ('31', '8', '2', '100'), ('32', '8', '3', '67'), ('33', '8', '4', '88'), ('34', '9', '1', '91'), ('35', '9', '2', '88'), ('36', '9', '3', '67'), ('37', '9', '4', '22'), ('38', '10', '1', '90'), ('39', '10', '2', '77'), ('40', '10', '3', '43'), ('41', '10', '4', '87'), ('42', '11', '1', '90'), ('43', '11', '2', '77'), ('44', '11', '3', '43'), ('45', '11', '4', '87'), ('46', '12', '1', '90'), ('47', '12', '2', '77'), ('48', '12', '3', '43'), ('49', '12', '4', '87'), ('52', '13', '3', '87');
    COMMIT;
    
    -- ----------------------------
    --  Table structure for `student`
    -- ----------------------------
    DROP TABLE IF EXISTS `student`;
    CREATE TABLE `student` (
      `sid` int(11) NOT NULL AUTO_INCREMENT,
      `gender` char(1) NOT NULL,
      `class_id` int(11) NOT NULL,
      `sname` varchar(32) NOT NULL,
      PRIMARY KEY (`sid`),
      KEY `fk_class` (`class_id`),
      CONSTRAINT `fk_class` FOREIGN KEY (`class_id`) REFERENCES `class` (`cid`)
    ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    --  Records of `student`
    -- ----------------------------
    BEGIN;
    INSERT INTO `student` VALUES ('1', '', '1', '理解'), ('2', '', '1', '钢蛋'), ('3', '', '1', '张三'), ('4', '', '1', '张一'), ('5', '', '1', '张二'), ('6', '', '1', '张四'), ('7', '', '2', '铁锤'), ('8', '', '2', '李三'), ('9', '', '2', '李一'), ('10', '', '2', '李二'), ('11', '', '2', '李四'), ('12', '', '3', '如花'), ('13', '', '3', '刘三'), ('14', '', '3', '刘一'), ('15', '', '3', '刘二'), ('16', '', '3', '刘四');
    COMMIT;
    
    -- ----------------------------
    --  Table structure for `teacher`
    -- ----------------------------
    DROP TABLE IF EXISTS `teacher`;
    CREATE TABLE `teacher` (
      `tid` int(11) NOT NULL AUTO_INCREMENT,
      `tname` varchar(32) NOT NULL,
      PRIMARY KEY (`tid`)
    ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    --  Records of `teacher`
    -- ----------------------------
    BEGIN;
    INSERT INTO `teacher` VALUES ('1', '张磊老师'), ('2', '李平老师'), ('3', '刘海燕老师'), ('4', '朱云海老师'), ('5', '李杰老师');
    COMMIT;
    
    SET FOREIGN_KEY_CHECKS = 1;
    复制代码

    从init.sql文件中导入数据

    #准备表、记录
    mysql> create database db1;
    mysql> use db1;
    mysql> source /root/init.sql

    !!!重中之重:练习之前务必搞清楚sql逻辑查询语句的执行顺序

    链接:http://www.cnblogs.com/linhaifeng/articles/7372774.html

    复制代码
    1、查询所有的课程的名称以及对应的任课老师姓名
    
    2、查询学生表中男女生各有多少人
    
    3、查询物理成绩等于100的学生的姓名
    
    4、查询平均成绩大于八十分的同学的姓名和平均成绩
    
    5、查询所有学生的学号,姓名,选课数,总成绩
    
    6、 查询姓李老师的个数
    
    7、 查询没有报李平老师课的学生姓名
    
    8、 查询物理课程比生物课程高的学生的学号
    
    9、 查询没有同时选修物理课程和体育课程的学生姓名
    
    10、查询挂科超过两门(包括两门)的学生姓名和班级
    
    11 、查询选修了所有课程的学生姓名
    
    12、查询李平老师教的课程的所有成绩记录
     
    13、查询全部学生都选修了的课程号和课程名
    
    14、查询每门课程被选修的次数
    
    15、查询之选修了一门课程的学生姓名和学号
    
    16、查询所有学生考出的成绩并按从高到低排序(成绩去重)
    
    17、查询平均成绩大于85的学生姓名和平均成绩
    
    18、查询生物成绩不及格的学生姓名和对应生物分数
    
    19、查询在所有选修了李平老师课程的学生中,这些课程(李平老师的课程,不是所有课程)平均成绩最高的学生姓名
    
    20、查询每门课程成绩最好的前两名学生姓名
    
    21、查询不同课程但成绩相同的学号,课程号,成绩
    
    22、查询没学过“叶平”老师课程的学生姓名以及选修的课程名称;
    
    23、查询所有选修了学号为1的同学选修过的一门或者多门课程的同学学号和姓名;
    
    24、任课最多的老师中学生单科成绩最高的学生姓名
    复制代码
    复制代码
    参考答案:
    
    1、SELECT cname,tname FROM course LEFT JOIN teacher on course.teacher_id=teacher.tid
    
    2、SELECT gender 性别 ,COUNT(gender) 人数 from student GROUP BY gender;
    
    3、SELECT sname from student where sid in (SELECT student_id from score LEFT JOIN course ON  
    
                       score.course_id=course.cid WHERE num=100 AND course.cname="物理");
    
     4、SELECT sname 姓名,平均成绩 from student RIGHT JOIN (SELECT student_id,avg(num) 平均成绩 from score                                            GROUP BY student_id HAVING avg(num)>80) as A
                                    on student.sid=A.student_id;
    
    5、SELECT  student_id 学号,sname 姓名,COUNT(course_id) 课程数,SUM(num) 总分 FROM score LEFT JOIN student 
                                    ON score.student_id=student.sid GROUP BY student_id;
    6、略
    
    7、SELECT * FROM student WHERE sid not in (SELECT student_id FROM score WHERE course_id in (SELECT cid                   FROM course LEFT JOIN teacher ON teacher.tid=course.teacher_id WHERE tname like "李平%"))
    
    
    8、     SELECT * FROM
    
            (SELECT * FROM score LEFT JOIN course ON score.course_id=course.cid WHERE cname="生物") as A
    
        INNER JOIN
    
            (SELECT * FROM score LEFT JOIN course ON score.course_id=course.cid WHERE cname="物理") as B
    
    
        ON A.student_id=B.student_id
    
        WHERE a.num<b.num
    
    9、SELECT sname from student WHERE sid NOT IN (SELECT student_id FROM score LEFT JOIN course ON 
            score.course_id=course.cid WHERE cname='体育'  OR cname='物理' GROUP BY student_id HAVING COUNT(course_id)>1) ;
    
    10、SELECT sname,gender from student WHERE sid in (SELECT student_id from score WHERE num<60 GROUP BY 
            student_id HAVING COUNT(student_id)>1);
    
    11、SELECT sid 学号,sname 姓名 from student WHERE sid in (SELECT student_id FROM score GROUP BY 
                    student_id HAVING COUNT(student_id)!= (SELECT COUNT(cid) FROM course))
    
    12、SELECT * FROM score WHERE course_id NOT IN (SELECT cid from teacher INNER JOIN course on
                          teacher.tid=course.teacher_id WHERE teacher.tname LIKE "李平%");
                
    13、SELECT course_id from score GROUP BY course_id HAVING COUNT(course_id)=(SELECT COUNT(sid) FROM 
                 student)
    
    14、--  SELECT course_id,COUNT(course_id) from score GROUP BY course_id
    
    
        SELECT cname,COUNT(course_id) FROM score LEFT JOIN course ON score.course_id=course.cid GROUP BY course_id
    
    15、SELECT sid,sname FROM student  WHERE sid in (SELECT student_id from score GROUP BY student_id 
            HAVING COUNT(sid)=1);
    
    
    16、SELECT DISTINCT num FROM score ORDER BY num DESC
    
    17、SELECT sname from student WHERE sid in (SELECT student_id FROM score GROUP BY student_id  HAVING
             AVG(num)>85)
           注意:用这种方式我们无法查看对应的平均成绩,所以不得不使用连表:
           SELECT sname,AVG(num) FROM student LEFT JOIN score ON student.sid=score.student_id GROUP BY student_id HAVING AVG(num)>85;
    
    18、SELECT sname 姓名,num 生物成绩 FROM score 
                     LEFT JOIN course ON score.course_id=course.cid 
                     LEFT JOIN student ON score.student_id=student.sid
    
                     WHERE score.num<60 AND cname="生物";
    
    19、
          方法1:
          SELECT student_id,avg(num),sname FROM score 
         LEFT JOIN student ON score.student_id=student.sid
                 WHERE course_id in (SELECT cid FROM course LEFT JOIN teacher ON teacher.tid=course.teacher_id WHERE tname LIKE "李平%")
                 GROUP BY student_id
         ORDER BY AVG(num) DESC
         LIMIT 1
    
         方法2:
    
         SELECT sname,MAX(B) FROM 
    
        (SELECT student_id,sname,AVG(num) as B FROM score 
                                 LEFT JOIN student ON score.student_id=student.sid
    
                     WHERE course_id in (SELECT cid FROM course LEFT JOIN teacher ON teacher.tid=course.teacher_id WHERE tname LIKE "李平%")
                     
                                
                                 GROUP BY student_id
    
        ) as A
    
     WHERE B=(
    
        SELECT MAX(B) FROM
         (SELECT student_id,sname,AVG(num) as B FROM score 
                                 LEFT JOIN student ON score.student_id=student.sid
    
                     WHERE course_id in (SELECT cid FROM course LEFT JOIN teacher ON teacher.tid=course.teacher_id WHERE tname LIKE "李平%")
                     
                                
                                 GROUP BY student_id
    
        ) as A
                         )
    复制代码

    参考答案:http://www.cnblogs.com/wupeiqi/articles/5748496.html

    实例:

    select 分组字段,count(id) from t1 where 条件 group by 分组字段
    
    max
    min
    sum
    avg
    
    group_concat
    
    #关键字执行优先级
    from
    where
    group by
    按照select后的字段取得一张新的虚拟表,有聚合函数则执行聚合函数
    having
    
    
    select max(salary) from t1 where id > 2 group by depart_id having count(id) > 2;
    select 333333333 from t1 where id > 2 group by depart_id having 4 > 2;
    
    #练习
    select post,count(id),group_concat(name) from emp group by post having count(id) < 2;
    
    
    select post,avg(salary) as 平均工资 from emp group by post having avg(salary) > 10000;
    select post 岗位名,avg(salary) 平均工资 from emp group by post having avg(salary) > 10000;
    
    
    
    #order by关键字
    select * from emp order by salary;
    select * from emp order by salary asc; #升序
    select * from emp order by salary desc; #降序
    
     select * from emp order by age asc,salary desc; #先按照年龄从小到大排,如果年龄分不出胜负(即值相同)再按照salary从大到小排。
    
    #练习:
    
    select * from emp order by age asc,hire_date desc;
    
    select post 岗位名,avg(salary) 平均工资 from emp group by post having avg(salary) > 10000 order by avg(salary) asc;
    
    
    
    #limit
    mysql> select * from emp limit 10;
    #从哪开始,往后取几条
    mysql> select * from emp limit 0,3;
    mysql> select * from emp limit 3,3;
    mysql> select * from emp limit 6,3;
    
    
    select name,id from emp where id>15 having id > 16;
    
    
    #distinct
    mysql> select * from emp limit 0,3;
    
    
    #多表查询
    create table department(
    id int primary key auto_increment,
    name varchar(20)
    );
    
    create table employee(
    id int primary key auto_increment,
    name varchar(20),
    sex enum('male','female') not null default 'male',
    age int,
    dep_id int,
    foreign key(dep_id) references department(id)
    );
    
    #简单查询
    select * from department,employee; #笛卡尔积
    select * from department,employee where department.id=employee.dep_id;
    
    #内连接:按照on条件只两张表的相同的部分,连接成一张虚拟的表
    select * from employee inner join department on department.id=employee.dep_id;
    select * from department inner join employee on department.id=employee.dep_id;
    #select * from employee,department where department.id=employee.dep_id;
    
    
    
    #左链接:在按照on的条件取到两张表共同部分的基础上,保留左表的记录
    select * from employee left join department on department.id=employee.dep_id;
    
    #右链接:在按照on的条件取到两张表共同部分的基础上,保留右表的记录
    select * from employee right join department on department.id=employee.dep_id;
    
    #full jion:
    select * from employee left join department on department.id=employee.dep_id
    union
    select * from employee right join department on department.id=employee.dep_id;
    
    
    
    
    #子查询:
    mysql> select * from employee where dep_id in (select id from department where name in ('技术','销售'));
    +----+-----------+--------+------+--------+
    | id | name      | sex    | age  | dep_id |
    +----+-----------+--------+------+--------+
    |  1 | egon      | male   |   18 |    200 |
    |  4 | yuanhao   | female |   28 |    202 |
    |  5 | liwenzhou | male   |   18 |    200 |
    +----+-----------+--------+------+--------+
    3 rows in set (0.02 sec)
    
    
    #查询平均年龄在25岁以上的部门名
    select name from department where id in (
    select dep_id from employee group by dep_id having avg(age) > 25
    );
    #查看技术部员工姓名
    select name from employee where dep_id = (select id from department where name='技术');
    
    #查看小于2人的部门名
    select name from department where id in (
    select dep_id from employee group by dep_id having count(id) < 2
    )
    union
    select name from department where id not in (select distinct dep_id from employee);
    
    #提取空部门                              #有人的部门
    select * from department where id not in (select distinct dep_id from employee);
    
    
    或者:
    select name from department where id in
    (
    select dep_id from employee group by dep_id having count(id) < 2
    union
    select id from department where id not in (select distinct dep_id from employee)
    );
    
    #exists
    mysql> select * from employee where exists (select id from department where name='hahahahah');
    Empty set (0.00 sec)
    
    mysql> select * from employee where exists (select id from department where name='技术');
    +----+------------+--------+------+--------+
    | id | name       | sex    | age  | dep_id |
    +----+------------+--------+------+--------+
    |  1 | egon       | male   |   18 |    200 |
    |  2 | alex       | female |   48 |    201 |
    |  3 | wupeiqi    | male   |   38 |    201 |
    |  4 | yuanhao    | female |   28 |    202 |
    |  5 | liwenzhou  | male   |   18 |    200 |
    |  6 | jingliyang | female |   18 |    204 |
    +----+------------+--------+------+--------+
    6 rows in set (0.00 sec)

    mysql经典例题:

    1、查询所有的课程的名称以及对应的任课老师姓名
    select cname,tname from course left join teacher on course.teacher_id=teacher.tid;
    2、查询学生表中男女生各有多少人
    select gender,count(sid) from student group by gender;
    3、查询物理成绩等于100的学生的姓名
    #子查询的方式
    select sname from student where sid in
    (
    select student_id from score
        where course_id = (select cid from course where cname='物理') and num=100
    );
    #连表的方式
    select sname from student inner join
    (
    select student_id from score
        where course_id = (select cid from course where cname='物理') and num=100
    ) as a
    on a.student_id=student.sid
    ;
    
    4、查询平均成绩大于八十分的同学的姓名和平均成绩
    select student.sname,t1.平均成绩 from student inner join
    (select student_id,avg(num) 平均成绩 from score group by student_id having avg(num) > 80) as t1
    on student.sid=t1.student_id;
    5、查询所有学生的学号,姓名,选课数,总成绩
    select student.sid,sname 学生名,选课数,总成绩 from student left join
    (select student_id,count(course_id) 选课数,sum(num) 总成绩 from score group by student_id) as t1
    on student.sid=t1.student_id
    ;
    6、 查询姓李老师的个数
    select count(tid) from teacher where tname like '李%';
    
    7、 查询没有报李平老师课的学生姓名
    select sname from student where sid not in (
    select distinct student_id from score where course_id in (
    select cid from course where teacher_id=(select tid from teacher where tname='李平老师')
    )
    );
    8、 查询物理课程比生物课程高的学生的学号
    select t1.student_id from
    (select student_id,num from score inner join course on score.course_id=course.cid
     where course.cname='物理') as t1
     inner join
    (select student_id,num from score inner join course on score.course_id=course.cid
    where course.cname='生物') as t2
    on t1.student_id=t2.student_id
    where t1.num > t2.num
    ;
    9、 查询没有同时选修物理课程和体育课程的学生姓名
    select sname from student where sid in (
    select student_id from score inner join course
    on course.cname in ('物理','体育') and course.cid=score.course_id
    group by student_id having count(course_id) !=2
    );
    10、查询挂科超过两门(包括两门)的学生姓名和班级名字
    select t2.sname,class.caption from
    (select sname,class_id from student inner join (
    select student_id from score
    where num < 60 group by student_id having count(course_id) >=2
    ) as t1
    on student.sid=t1.student_id) as t2
    inner join class
    on class.cid = t2.class_id
    ;
    11 、查询选修了所有课程的学生姓名
    select sname from student inner join
    (
    select student_id from score group by student_id having count(course_id) = (select count(cid) from course)
    ) t1
    on t1.student_id = student.sid
    ;
    12、查询李平老师教的课程的所有成绩记录
    select student_id,course_id,num from score inner join
    (
    select cid from course inner join teacher on teacher.tname='李平老师' and teacher.tid=course.teacher_id
    ) as t1
    on t1.cid=score.course_id
    ;
    
    13、查询全部学生都选修了的课程号和课程名
    select course.cid,course.cname from course inner join
    (
    select course_id from score group by course_id
    having count(student_id) = (select count(sid) from student)
    ) t1
    on t1.course_id=course.cid
    ;
    
    14、查询每门课程被选修的次数
    select course.cname,选修人数 from course inner join
    (
    select course_id,count(student_id) as 选修人数 from score group by course_id
    ) as t1
    on t1.course_id=course.cid
    ;
    15、查询之选修了一门课程的学生姓名和学号
    select sid,sname from student inner join
    (
    select student_id from score group by student_id having count(course_id)=1
    ) t1
    on t1.student_id = student.sid
    ;
    16、查询所有学生考出的成绩并按从高到低排序(成绩去重)
    select distinct num from score order by num desc;
    
    17、查询平均成绩大于85的学生姓名和平均成绩
    select student.sname,avg_num from student inner join
    (
    select student_id,avg(num) as avg_num from score group by student_id having avg(num) > 85
    ) t1
    on student.sid=t1.student_id
    ;
    
    18、查询生物成绩不及格的学生姓名和对应生物分数
    select student.sname,t1.num from student inner join
    (
    select student_id,num from score
    where course_id=(select cid from course where cname='生物') and num < 60
    ) t1
    on t1.student_id=student.sid
    ;
    19、查询在所有选修了李平老师课程的学生中,这些课程(李平老师的课程,不是所有课程)平均成绩最高的学生姓名
    
    select sname from student where sid =
    (
    select student_id from score where course_id in
    (
    select cid from course inner join teacher on teacher.tname='李平老师' and course.teacher_id=teacher.tid
    )
    group by student_id
    order by avg(num) desc
    limit 1
    );

     索引原理与慢查询优化:

    阅读目录

    索引介绍:

    为什么要有索引?

    一般的应用系统,读写比例在10:1左右,而且插入操作和一般的更新操作很少出现性能问题,在生产环境中,我们遇到最多的,也是最容易出问题的,还是一些复杂的查询操作,因此对查询语句的优化显然是重中之重,说起来所谓的索引就是为了能过够加速查询的(这个时候我们就不能不用索引了)。

     

    什么是索引?

     

    索引在MySQL中也叫做“键”,是存储引擎用于快速找到记录的一种数据结构。索引对于良好的性能
    非常关键,尤其是当表中的数据量越来越大时,索引对于性能的影响愈发重要。
    索引优化应该是对查询性能优化最有效的手段了。索引能够轻易将查询性能提高好几个数量级。
    索引相当于字典的音序表,如果要查某个字,如果不使用音序表,则需要从几百页中逐页去查。

    索引原理:

    索引的原理简单来讲就是,为了提高查询的效率,它的本质就是,不断的缩小要获取数据的范围来帅选出最终想要的结果,同时把随机的时间变成顺序的时间也就是说,有了这种索引机制,我们可以总是用同一种查找方式来锁定数据。

    数据库也是一样,但显然要复杂的多,因为不仅面临着等值查询,还有范围查询(>、<、between、in)、模糊查询(like)、并集查询(or)等等。数据库应该选择怎么样的方式来应对所有的问题呢?我们回想字典的例子,能不能把数据分成段,然后分段查询呢?最简单的如果1000条数据,1到100分成第一段,101到200分成第二段,201到300分成第三段......这样查第250条数据,只要找第三段就可以了,一下子去除了90%的无效数据。但如果是1千万的记录呢,分成几段比较好?稍有算法基础的同学会想到搜索树,其平均复杂度是lgN,具有不错的查询性能。但这里我们忽略了一个关键的问题,复杂度模型是基于每次相同的操作成本来考虑的。而数据库实现比较复杂,一方面数据是保存在磁盘上的,另外一方面为了提高性能,每次又可以把部分数据读入内存来计算,因为我们知道访问磁盘的成本大概是访问内存的十万倍左右,所以简单的搜索树难以满足复杂的应用场景。

    二 磁盘IO与预读

    前面提到了访问磁盘,那么这里先简单介绍一下磁盘IO和预读,磁盘读取数据靠的是机械运动,每次读取数据花费的时间可以分为寻道时间、旋转延迟、传输时间三个部分,寻道时间指的是磁臂移动到指定磁道所需要的时间,主流磁盘一般在5ms以下;旋转延迟就是我们经常听说的磁盘转速,比如一个磁盘7200转,表示每分钟能转7200次,也就是说1秒钟能转120次,旋转延迟就是1/120/2 = 4.17ms;传输时间指的是从磁盘读出或将数据写入磁盘的时间,一般在零点几毫秒,相对于前两个时间可以忽略不计。那么访问一次磁盘的时间,即一次磁盘IO的时间约等于5+4.17 = 9ms左右,听起来还挺不错的,但要知道一台500 -MIPS(Million Instructions Per Second)的机器每秒可以执行5亿条指令,因为指令依靠的是电的性质,换句话说执行一次IO的时间可以执行约450万条指令,数据库动辄十万百万乃至千万级数据,每次9毫秒的时间,显然是个灾难。下图是计算机硬件延迟的对比图,供大家参考:

     

    考虑到磁盘IO是非常高昂的操作,计算机操作系统做了一些优化,当一次IO时,不光把当前磁盘地址的数据,而是把相邻的数据也都读取到内存缓冲区内,因为局部预读性原理告诉我们,当计算机访问一个地址的数据的时候,与其相邻的数据也会很快被访问到。每一次IO读取的数据我们称之为一页(page)。具体一页有多大数据跟操作系统有关,一般为4k或8k,也就是我们读取一页内的数据时候,实际上才发生了一次IO,这个理论对于索引的数据结构设计非常有帮助。

    三 索引的数据结构

    前面讲了索引的基本原理,数据库的复杂性,又讲了操作系统的相关知识,目的就是让大家了解,任何一种数据结构都不是凭空产生的,一定会有它的背景和使用场景,我们现在总结一下,我们需要这种数据结构能够做些什么,其实很简单,那就是:每次查找数据时把磁盘IO次数控制在一个很小的数量级,最好是常数数量级。那么我们就想到如果一个高度可控的多路搜索树是否能满足需求呢?就这样,b+树应运而生。

    如上图,是一颗b+树,关于b+树的定义可以参见B+树,这里只说一些重点,浅蓝色的块我们称之为一个磁盘块,可以看到每个磁盘块包含几个数据项(深蓝色所示)和指针(黄色所示),如磁盘块1包含数据项17和35,包含指针P1、P2、P3,P1表示小于17的磁盘块,P2表示在17和35之间的磁盘块,P3表示大于35的磁盘块。真实的数据存在于叶子节点即3、5、9、10、13、15、28、29、36、60、75、79、90、99。非叶子节点只不存储真实的数据,只存储指引搜索方向的数据项,如17、35并不真实存在于数据表中。

    ###b+树的查找过程
    如图所示,如果要查找数据项29,那么首先会把磁盘块1由磁盘加载到内存,此时发生一次IO,在内存中用二分查找确定29在17和35之间,锁定磁盘块1的P2指针,内存时间因为非常短(相比磁盘的IO)可以忽略不计,通过磁盘块1的P2指针的磁盘地址把磁盘块3由磁盘加载到内存,发生第二次IO,29在26和30之间,锁定磁盘块3的P2指针,通过指针加载磁盘块8到内存,发生第三次IO,同时内存中做二分查找找到29,结束查询,总计三次IO。真实的情况是,3层的b+树可以表示上百万的数据,如果上百万的数据查找只需要三次IO,性能提高将是巨大的,如果没有索引,每个数据项都要发生一次IO,那么总共需要百万次的IO,显然成本非常非常高。

    ###b+树性质
    1.索引字段要尽量的小:通过上面的分析,我们知道IO次数取决于b+数的高度h,假设当前数据表的数据为N,每个磁盘块的数据项的数量是m,则有h=㏒(m+1)N,当数据量N一定的情况下,m越大,h越小;而m = 磁盘块的大小 / 数据项的大小,磁盘块的大小也就是一个数据页的大小,是固定的,如果数据项占的空间越小,数据项的数量越多,树的高度越低。这就是为什么每个数据项,即索引字段要尽量的小,比如int占4字节,要比bigint8字节少一半。这也是为什么b+树要求把真实的数据放到叶子节点而不是内层节点,一旦放到内层节点,磁盘块的数据项会大幅度下降,导致树增高。当数据项等于1时将会退化成线性表。
    2.索引的最左匹配特性:当b+树的数据项是复合的数据结构,比如(name,age,sex)的时候,b+数是按照从左到右的顺序来建立搜索树的,比如当(张三,20,F)这样的数据来检索的时候,b+树会优先比较name来确定下一步的所搜方向,如果name相同再依次比较age和sex,最后得到检索的数据;但当(20,F)这样的没有name的数据来的时候,b+树就不知道下一步该查哪个节点,因为建立搜索树的时候name就是第一个比较因子,必须要先根据name来搜索才能知道下一步去哪里查询。比如当(张三,F)这样的数据来检索时,b+树可以用name来指定搜索方向,但下一个字段age的缺失,所以只能把名字等于张三的数据都找到,然后再匹配性别是F的数据了, 这个是非常重要的性质,即索引的最左匹配特性。

    三 MySQL索引管理

    MySQL的索引分类

    普通索引 index:加速查找
    
    
    唯一索引:
        主键索引 primary key: 加速查找+约束(不为空,不能重复)
        唯一索引 unique:加速查找+约束(不能重复)
    
    联合索引:
        primary key(id,name):联合主键索引
        unique (id,name):联合唯一索引
        index(id,name):联合普通索引
    举个例子来说,比如你在为某商场做一个会员卡的系统。
    
    这个系统有一个会员表
    有下列字段:
    会员编号 INT
    会员姓名 VARCHAR(10)
    会员身份证号码 VARCHAR(18)
    会员电话 VARCHAR(10)
    会员住址 VARCHAR(50)
    会员备注信息 TEXT
    
    那么这个 会员编号,作为主键,使用 PRIMARY
    会员姓名 如果要建索引的话,那么就是普通的 INDEX
    会员身份证号码 如果要建索引的话,那么可以选择 UNIQUE (唯一的,不允许重复)
    
    #除此之外还有全文索引,即FULLTEXT
    会员备注信息 , 如果需要建索引的话,可以选择全文搜索。
    用于搜索很长一篇文章的时候,效果最好。
    用在比较短的文本,如果就一两行字的,普通的 INDEX 也可以。
    但其实对于全文搜索,我们并不会使用MySQL自带的该索引,而是会选择第三方软件如Sphinx,专门来做全文搜索。
    
    #其他的如空间索引SPATIAL,了解即可,几乎不用
    各个索引的应用场景

    三 索引的两大类型hash与btree

    #我们可以在创建上述索引的时候,为其指定索引类型,分两类
    hash类型的索引:查询单条快,范围查询慢
    btree类型的索引:b+树,层数越多,数据量指数级增长(我们就用它,因为innodb默认支持它)
    
    #不同的存储引擎支持的索引类型也不一样
    InnoDB 支持事务,支持行级别锁定,支持 B-tree、Full-text 等索引,不支持 Hash 索引;
    MyISAM 不支持事务,支持表级别锁定,支持 B-tree、Full-text 等索引,不支持 Hash 索引;
    Memory 不支持事务,支持表级别锁定,支持 B-tree、Hash 等索引,不支持 Full-text 索引;
    NDB 支持事务,支持行级别锁定,支持 Hash 索引,不支持 B-tree、Full-text 等索引;
    Archive 不支持事务,支持表级别锁定,不支持 B-tree、Hash、Full-text 等索引

    四 创建/删除索引的语法

    方法一:创建表的时候
        CREATE TABLE 表名 (
                    字段名1  数据类型 [完整性约束条件…],
                    字段名2  数据类型 [完整性约束条件…],
                    [UNIQUE | FULLTEXT | SPATIAL ]   INDEX | KEY
                    [索引名]  (字段名[(长度)]  [ASC |DESC]) 
                    );
    方法二:create 在已经存在的表上创建表上创建索引
         CREATE  [UNIQUE | FULLTEXT | SPATIAL ]  INDEX  索引名 
                         ON 表名 (字段名[(长度)]  [ASC |DESC]) ;
    方法三:alter table 在已存在的表上创建索引
        ALTER TABLE 表名 ADD  [UNIQUE | FULLTEXT | SPATIAL ] INDEX
                                 索引名 (字段名[(长度)]  [ASC |DESC]) ;
    
    删除索引:
        drop index 索引名 on 表名

    四 测试索引

    1 准备

    #1. 准备表
    create table s1(
    id int,
    name varchar(20),
    gender char(6),
    email varchar(50)
    );
    
    #2. 创建存储过程,实现批量插入记录
    delimiter $$ #声明存储过程的结束符号为$$
    create procedure auto_insert1()
    BEGIN
        declare i int default 1;
        while(i<3000000)do
            insert into s1 values(i,concat('egon',i),'male',concat('egon',i,'@oldboy'));
            set i=i+1;
        end while;
    END$$ #$$结束
    delimiter ; #重新声明分号为结束符号
    
    #3. 查看存储过程
    show create procedure auto_insert1G 
    
    #4. 调用存储过程
    call auto_insert1();
    复制代码

    2 在没有索引的前提下测试查询速度

    #无索引:从头到尾扫描一遍,所以查询速度很慢
    mysql> select * from s1 where id=333;
    +------+---------+--------+----------------+
    | id   | name    | gender | email          |
    +------+---------+--------+----------------+
    |  333 | egon333 | male   | 333@oldboy.com |
    |  333 | egon333 | f      | alex333@oldboy |
    |  333 | egon333 | f      | alex333@oldboy |
    +------+---------+--------+----------------+
    3 rows in set (0.32 sec)
    
    mysql> select * from s1 where email='egon333@oldboy';
    ....
    ... rows in set (0.36 sec)

    三 在表中已经存在大量数据的前提下,为某个字段段建立索引,建立速度会很慢

    四 在索引建立完毕后,以该字段为查询条件时,查询速度提升明显

    PS:

    1. mysql先去索引表里根据b+树的搜索原理很快搜索到id等于333333333的记录不存在,IO大大降低,因而速度明显提升

    2. 我们可以去mysql的data目录下找到该表,可以看到占用的硬盘空间多了

    3. 需要注意,如下图

    五 总结

    复制代码
    #1. 一定是为搜索条件的字段创建索引,比如select * from s1 where id = 333;就需要为id加上索引
    
    #2. 在表中已经有大量数据的情况下,建索引会很慢,且占用硬盘空间,建完后查询速度加快
    比如create index idx on s1(id);会扫描表中所有的数据,然后以id为数据项,创建索引结构,存放于硬盘的表中。
    建完以后,再查询就会很快了。
    
    #3. 需要注意的是:innodb表的索引会存放于s1.ibd文件中,而myisam表的索引则会有单独的索引文件table1.MYI
    复制代码

    五 正确使用索引

    一 索引未命中

    并不是说我们创建了索引就一定会加快查询速度,若想利用索引达到预想的提高查询速度的效果,我们在添加索引时,必须遵循以下问题

    1 范围问题,或者说条件不明确,条件中出现这些符号或关键字:>、>=、<、<=、!= 、between...and...、like、

    大于号、小于号

    不等于!=

    between ...and...

    like

    2 尽量选择区分度高的列作为索引,区分度的公式是count(distinct col)/count(*),表示字段不重复的比例,比例越大我们扫描的记录数越少,唯一键的区分度是1,而一些状态、性别字段可能在大数据面前区分度就是0,那可能有人会问,这个比例有什么经验值吗?使用场景不同,这个值也很难确定,一般需要join的字段我们都要求是0.1以上,即平均1条扫描10条记录

     #先把表中的索引都删除,让我们专心研究区分度的问题

     分析原因

    3 =和in可以乱序,比如a = 1 and b = 2 and c = 3 建立(a,b,c)索引可以任意顺序,mysql的查询优化器会帮你优化成索引可以识别的形式

    4 索引列不能参与计算,保持列“干净”,比如from_unixtime(create_time) = ’2014-05-29’就不能使用到索引,原因很简单,b+树中存的都是数据表中的字段值,但进行检索时,需要把所有元素都应用函数才能比较,显然成本太大。所以语句应该写成create_time = unix_timestamp(’2014-05-29’)

    5 and

    条件1 and 条件2:在条件1不成立的情况下,不会再去判断条件2,此时若条件1的字段有索引,而条件2没有,那么查询速度依然很快

    在左边条件成立但是索引字段的区分度低的情况下(name与gender均属于这种情况),会依次往右找到一个区分度高的索引字段,加速查询

    经过分析,在条件为name='egon' and gender='male' and id>333 and email='xxx'的情况下,我们完全没必要为前三个条件的字段加索引,因为只能用上email字段的索引,前三个字段的索引反而会降低我们的查询效率

    6 最左前缀匹配原则,非常重要的原则,对于组合索引mysql会一直向右匹配直到遇到范围查询(>、<、between、like)就停止匹配,比如a = 1 and b = 2 and c > 3 and d = 4 如果建立(a,b,c,d)顺序的索引,d是用不到索引的,如果建立(a,b,d,c)的索引则都可以用到,a,b,d的顺序可以任意调整。

    7 其他情况

     View Code

    其他注意事项

    复制代码
    - 避免使用select *
    - count(1)或count(列) 代替 count(*)
    - 创建表时尽量时 char 代替 varchar
    - 表的字段顺序固定长度的字段优先
    - 组合索引代替多个单列索引(经常使用多个条件查询时)
    - 尽量使用短索引
    - 使用连接(JOIN)来代替子查询(Sub-Queries)
    - 连表时注意条件类型需一致
    - 索引散列值(重复少)不适合建索引,例:性别不适合
    复制代码

    三 覆盖索引与索引合并

    复制代码
    #覆盖索引:
        - 在索引文件中直接获取数据
        http://blog.itpub.net/22664653/viewspace-774667/
    
    #分析
    select * from s1 where id=123;
    该sql命中了索引,但未覆盖索引。
    利用id=123到索引的数据结构中定位到该id在硬盘中的位置,或者说再数据表中的位置。
    但是我们select的字段为*,除了id以外还需要其他字段,这就意味着,我们通过索引结构取到id还不够,还需要利用该id再去找到该id所在行的其他字段值,这是需要时间的,很明显,如果我们只select id,就减去了这份苦恼,如下
    select id from s1 where id=123;
    这条就是覆盖索引了,命中索引,且从索引的数据结构直接就取到了id在硬盘的地址,速度很快
    复制代码
    复制代码
    #索引合并:把多个单列索引合并使用
    
    #分析:
    组合索引能做到的事情,我们都可以用索引合并去解决,比如
    create index ne on s1(name,email);#组合索引
    我们完全可以单独为name和email创建索引
    
    组合索引可以命中:
    select * from s1 where name='egon' ;
    select * from s1 where name='egon' and email='adf';
    
    索引合并可以命中:
    select * from s1 where name='egon' ;
    select * from s1 where email='adf';
    select * from s1 where name='egon' and email='adf';
    
    乍一看好像索引合并更好了:可以命中更多的情况,但其实要分情况去看,如果是name='egon' and email='adf',那么组合索引的效率要高于索引合并,如果是单条件查,那么还是用索引合并比较合理
    复制代码

    六 查询优化神器-explain

    关于explain命令相信大家并不陌生,具体用法和字段含义可以参考官网explain-output,这里需要强调rows是核心指标,绝大部分rows小的语句执行一定很快(有例外,下面会讲到)。所以优化语句基本上都是在优化rows。

    复制代码
    执行计划:让mysql预估执行操作(一般正确)
        all < index < range < index_merge < ref_or_null < ref < eq_ref < system/const
        id,email
        
        慢:
            select * from userinfo3 where name='alex'
            
            explain select * from userinfo3 where name='alex'
            type: ALL(全表扫描)
                select * from userinfo3 limit 1;
        快:
            select * from userinfo3 where email='alex'
            type: const(走索引)
    复制代码

    http://blog.itpub.net/29773961/viewspace-1767044/

    七 慢查询优化的基本步骤

    复制代码
    0.先运行看看是否真的很慢,注意设置SQL_NO_CACHE
    1.where条件单表查,锁定最小返回记录表。这句话的意思是把查询语句的where都应用到表中返回的记录数最小的表开始查起,单表每个字段分别查询,看哪个字段的区分度最高
    2.explain查看执行计划,是否与1预期一致(从锁定记录较少的表开始查询)
    3.order by limit 形式的sql语句让排序的表优先查
    4.了解业务方使用场景
    5.加索引时参照建索引的几大原则
    6.观察结果,不符合预期继续从0分析
    复制代码

    八 慢日志管理

    复制代码
            慢日志
                - 执行时间 > 10
                - 未命中索引
                - 日志文件路径
                
            配置:
                - 内存
                    show variables like '%query%';
                    show variables like '%queries%';
                    set global 变量名 = 值
                - 配置文件
                    mysqld --defaults-file='E:wupeiqimysql-5.7.16-winx64mysql-5.7.16-winx64my-default.ini'
                    
                    my.conf内容:
                        slow_query_log = ON
                        slow_query_log_file = D:/....
                        
                    注意:修改配置文件之后,需要重启服务
    复制代码
    复制代码
    MySQL日志管理
    ========================================================
    错误日志: 记录 MySQL 服务器启动、关闭及运行错误等信息
    二进制日志: 又称binlog日志,以二进制文件的方式记录数据库中除 SELECT 以外的操作
    查询日志: 记录查询的信息
    慢查询日志: 记录执行时间超过指定时间的操作
    中继日志: 备库将主库的二进制日志复制到自己的中继日志中,从而在本地进行重放
    通用日志: 审计哪个账号、在哪个时段、做了哪些事件
    事务日志或称redo日志: 记录Innodb事务相关的如事务执行时间、检查点等
    ========================================================
    一、bin-log
    1. 启用
    # vim /etc/my.cnf
    [mysqld]
    log-bin[=dir[filename]]
    # service mysqld restart
    2. 暂停
    //仅当前会话
    SET SQL_LOG_BIN=0;
    SET SQL_LOG_BIN=1;
    3. 查看
    查看全部:
    # mysqlbinlog mysql.000002
    按时间:
    # mysqlbinlog mysql.000002 --start-datetime="2012-12-05 10:02:56"
    # mysqlbinlog mysql.000002 --stop-datetime="2012-12-05 11:02:54"
    # mysqlbinlog mysql.000002 --start-datetime="2012-12-05 10:02:56" --stop-datetime="2012-12-05 11:02:54" 
    
    按字节数:
    # mysqlbinlog mysql.000002 --start-position=260
    # mysqlbinlog mysql.000002 --stop-position=260
    # mysqlbinlog mysql.000002 --start-position=260 --stop-position=930
    4. 截断bin-log(产生新的bin-log文件)
    a. 重启mysql服务器
    b. # mysql -uroot -p123 -e 'flush logs'
    5. 删除bin-log文件
    # mysql -uroot -p123 -e 'reset master' 
    
    
    二、查询日志
    启用通用查询日志
    # vim /etc/my.cnf
    [mysqld]
    log[=dir[filename]]
    # service mysqld restart
    
    三、慢查询日志
    启用慢查询日志
    # vim /etc/my.cnf
    [mysqld]
    log-slow-queries[=dir[filename]]
    long_query_time=n
    # service mysqld restart
    MySQL 5.6:
    slow-query-log=1
    slow-query-log-file=slow.log
    long_query_time=3
    查看慢查询日志
    测试:BENCHMARK(count,expr)
    SELECT BENCHMARK(50000000,2*3);
    复制代码

    九 参考博客

    https://tech.meituan.com/mysql-index.html 

    http://blog.itpub.net/29773961/viewspace-1767044/
    http://www.cnblogs.com/wupeiqi/articles/5716963.html

    http://www.cnblogs.com/hustcat/archive/2009/10/28/1591648.html
    http://www.cnblogs.com/mr-wid/archive/2013/05/09/3068229.html
    http://www.cnblogs.com/kissdodog/p/4159176.html
    http://blog.csdn.net/ggxxkkll/article/details/7551766
    http://blog.itpub.net/26435490/viewspace-1133659/
    http://pymysql.readthedocs.io/en/latest/user/examples.html
    http://www.cnblogs.com/lyhabc/p/3793524.html
    http://www.jianshu.com/p/ed32d69383d2
    http://doc.mysql.cn/mysql5/refman-5.1-zh.html-chapter/
    http://doc.mysql.cn/
    http://www.php100.com/html/webkaifa/database/Mysql/2013/0316/12223.html
    http://blog.csdn.net/ltylove2007/article/details/21084809
    http://lib.csdn.net/base/mysql
    http://blog.csdn.net/c_enhui/article/details/9021271
    http://www.cnblogs.com/edisonchou/p/3878135.html?utm_source=tuicool&utm_medium=referral
    http://www.cnblogs.com/ggjucheng/archive/2012/11/11/2765465.html
    http://www.cnblogs.com/cchust/p/3444510.html
    http://www.docin.com/p-705091183.html
    http://www.open-open.com/doc/view/51f552745f514bbbaf0aaecf6c88509a
    http://www.open-open.com/doc/view/f80947a5c805458db8cf929834d241bf
    http://www.open-open.com/lib/view/open1435498096607.html
    http://www.open-open.com/doc/view/48c510607ab84fd8b87b158c3fe9d177
    http://www.open-open.com/lib/view/open1448032294072.html
    http://www.open-open.com/lib/view/open1404887901263.html
    http://www.cnblogs.com/cchust/p/3426927.html
    http://wribao.php230.com/category/news/1138254.html
    http://www.iqiyi.com/w_19rqqds1ut.html
    http://wenku.baidu.com/link?url=7Grxv0cQ_a00Ni2ZEU_cbDk2Wd2VTzlnS2UPKST3OF4oDqoLUQ2rQpOmK8ap12RDnXbnNs6gbY8DXVvWmo9bMxjWGS_vkhYus22ghAZYuES
    http://www.cnblogs.com/edisonchou/p/3878135.html
    http://blog.chinaunix.net/uid-540802-id-3419311.html
    http://my.oschina.net/scipio/blog/293052
    http://blog.itpub.net/29773961/viewspace-1767044/
    http://my.oschina.net/lionets/blog/407263

     

    mysql七:数据备份、pymysql模块

     

    一 IDE工具介绍

    生产环境还是推荐使用mysql命令行,但为了方便我们测试,可以使用IDE工具

    下载链接:https://pan.baidu.com/s/1bpo5mqj

    复制代码
    掌握:
    #1. 测试+链接数据库
    #2. 新建库
    #3. 新建表,新增字段+类型+约束
    #4. 设计表:外键
    #5. 新建查询
    #6. 备份库/表
    
    #注意:
    批量加注释:ctrl+?键
    批量去注释:ctrl+shift+?键
    复制代码

    二 MySQL数据备份

    #1. 物理备份: 直接复制数据库文件,适用于大型数据库环境。但不能恢复到异构系统中如Windows。
    #2. 逻辑备份: 备份的是建表、建库、插入等操作所执行SQL语句,适用于中小型数据库,效率相对较低。
    #3. 导出表: 将表导入到文本文件中。 

    一、使用mysqldump实现逻辑备份

    复制代码
    #语法:
    # mysqldump -h 服务器 -u用户名 -p密码 数据库名 > 备份文件.sql
    
    #示例:
    #单库备份
    mysqldump -uroot -p123 db1 > db1.sql
    mysqldump -uroot -p123 db1 table1 table2 > db1-table1-table2.sql
    
    #多库备份
    mysqldump -uroot -p123 --databases db1 db2 mysql db3 > db1_db2_mysql_db3.sql
    
    #备份所有库
    mysqldump -uroot -p123 --all-databases > all.sql 
    复制代码

    二、恢复逻辑备份

    复制代码
    #方法一:
    [root@egon backup]# mysql -uroot -p123 < /backup/all.sql
    
    #方法二:
    mysql> use db1;
    mysql> SET SQL_LOG_BIN=0;
    mysql> source /root/db1.sql
    
    #注:如果备份/恢复单个库时,可以修改sql文件
    DROP database if exists school;
    create database school;
    use school; 
    复制代码

    三、备份/恢复案例

    复制代码
    #数据库备份/恢复实验一:数据库损坏
    备份:
    1. # mysqldump -uroot -p123 --all-databases > /backup/`date +%F`_all.sql
    2. # mysql -uroot -p123 -e 'flush logs' //截断并产生新的binlog
    3. 插入数据 //模拟服务器正常运行
    4. mysql> set sql_log_bin=0; //模拟服务器损坏
    mysql> drop database db;
    
    恢复:
    1. # mysqlbinlog 最后一个binlog > /backup/last_bin.log
    2. mysql> set sql_log_bin=0; 
    mysql> source /backup/2014-02-13_all.sql //恢复最近一次完全备份 
    mysql> source /backup/last_bin.log //恢复最后个binlog文件
    
    
    #数据库备份/恢复实验二:如果有误删除
    备份:
    1. mysqldump -uroot -p123 --all-databases > /backup/`date +%F`_all.sql
    2. mysql -uroot -p123 -e 'flush logs' //截断并产生新的binlog
    3. 插入数据 //模拟服务器正常运行
    4. drop table db1.t1 //模拟误删除
    5. 插入数据 //模拟服务器正常运行
    
    恢复:
    1. # mysqlbinlog 最后一个binlog --stop-position=260 > /tmp/1.sql 
    # mysqlbinlog 最后一个binlog --start-position=900 > /tmp/2.sql 
    2. mysql> set sql_log_bin=0; 
    mysql> source /backup/2014-02-13_all.sql //恢复最近一次完全备份
    mysql> source /tmp/1.log //恢复最后个binlog文件
    mysql> source /tmp/2.log //恢复最后个binlog文件
    
    注意事项:
    1. 完全恢复到一个干净的环境(例如新的数据库或删除原有的数据库)
    2. 恢复期间所有SQL语句不应该记录到binlog中
    复制代码

    四、实现自动化备份

    复制代码
    备份计划:
    1. 什么时间 2:00
    2. 对哪些数据库备份
    3. 备份文件放的位置
    
    备份脚本:
    [root@egon ~]# vim /mysql_back.sql
    #!/bin/bash
    back_dir=/backup
    back_file=`date +%F`_all.sql
    user=root
    pass=123
    
    if [ ! -d /backup ];then
    mkdir -p /backup
    fi
    
    # 备份并截断日志
    mysqldump -u${user} -p${pass} --events --all-databases > ${back_dir}/${back_file}
    mysql -u${user} -p${pass} -e 'flush logs'
    
    # 只保留最近一周的备份
    cd $back_dir
    find . -mtime +7 -exec rm -rf {} ;
    
    手动测试:
    [root@egon ~]# chmod a+x /mysql_back.sql 
    [root@egon ~]# chattr +i /mysql_back.sql
    [root@egon ~]# /mysql_back.sql
    
    配置cron:
    [root@egon ~]# crontab -l
    2 * * * /mysql_back.sql
    复制代码

    五、表的导出和导入

    复制代码
    SELECT... INTO OUTFILE 导出文本文件
    示例:
    mysql> SELECT * FROM school.student1
    INTO OUTFILE 'student1.txt'
    FIELDS TERMINATED BY ',' //定义字段分隔符
    OPTIONALLY ENCLOSED BY '' //定义字符串使用什么符号括起来
    LINES TERMINATED BY '
    ' ; //定义换行符
    
    
    mysql 命令导出文本文件
    示例:
    # mysql -u root -p123 -e 'select * from student1.school' > /tmp/student1.txt
    # mysql -u root -p123 --xml -e 'select * from student1.school' > /tmp/student1.xml
    # mysql -u root -p123 --html -e 'select * from student1.school' > /tmp/student1.html
    
    LOAD DATA INFILE 导入文本文件
    mysql> DELETE FROM student1;
    mysql> LOAD DATA INFILE '/tmp/student1.txt'
    INTO TABLE school.student1
    FIELDS TERMINATED BY ','
    OPTIONALLY ENCLOSED BY ''
    LINES TERMINATED BY '
    ';
    复制代码

    六、数据库迁移

    务必保证在相同版本之间迁移
    # mysqldump -h 源IP -uroot -p123 --databases db1 | mysql -h 目标IP -uroot -p456

    三 pymysql模块

    #安装
    pip3 install pymysql

    一 链接、执行sql、关闭(游标)

    复制代码
    import pymysql
    user=input('用户名: ').strip()
    pwd=input('密码: ').strip()
    
    #链接
    conn=pymysql.connect(host='localhost',user='root',password='123',database='egon',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('登录失败')
    复制代码

    二 execute()之sql注入

    注意:符号--会注释掉它之后的sql,正确的语法:--后至少有一个任意字符

    根本原理:就根据程序的字符串拼接name='%s',我们输入一个xxx' -- haha,用我们输入的xxx加'在程序中拼接成一个判断条件name='xxx' -- haha'

    复制代码
    最后那一个空格,在一条sql语句中如果遇到select * from t1 where id > 3 -- and name='egon';则--之后的条件被注释掉了
    
    #1、sql注入之:用户存在,绕过密码
    egon' -- 任意字符
    
    #2、sql注入之:用户不存在,绕过用户与密码
    xxx' or 1=1 -- 任意字符
    复制代码

     

    解决方法:

    复制代码
    # 原来是我们对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的规矩来。
    复制代码

    三 增、删、改:conn.commit()

     View Code

    四 查:fetchone,fetchmany,fetchall

    复制代码
    import pymysql
    #链接
    conn=pymysql.connect(host='localhost',user='root',password='123',database='egon')
    #游标
    cursor=conn.cursor()
    
    #执行sql语句
    sql='select * from userinfo;'
    rows=cursor.execute(sql) #执行sql语句,返回sql影响成功的行数rows,将结果放入一个集合,等待被查询
    
    # cursor.scroll(3,mode='absolute') # 相对绝对位置移动
    # cursor.scroll(3,mode='relative') # 相对当前位置移动
    res1=cursor.fetchone()
    res2=cursor.fetchone()
    res3=cursor.fetchone()
    res4=cursor.fetchmany(2)
    res5=cursor.fetchall()
    print(res1)
    print(res2)
    print(res3)
    print(res4)
    print(res5)
    print('%s rows in set (0.00 sec)' %rows)
    
    
    
    conn.commit() #提交后才发现表中插入记录成功
    cursor.close()
    conn.close()
    
    '''
    (1, 'root', '123456')
    (2, 'root', '123456')
    (3, 'root', '123456')
    ((4, 'root', '123456'), (5, 'root', '123456'))
    ((6, 'root', '123456'), (7, 'lhf', '12356'), (8, 'eee', '156'))
    rows in set (0.00 sec)
    '''
    复制代码

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

    复制代码
    import pymysql
    conn=pymysql.connect(host='localhost',user='root',password='123',database='egon')
    cursor=conn.cursor()
    
    sql='insert into userinfo(name,password) values("xxx","123");'
    rows=cursor.execute(sql)
    
    conn.commit()
    print(cursor.lastrowid) #在commit之前和之后都可以查看
    cursor.close()
    conn.close()
    复制代码

    mysql八:视图、触发器、事务、存储过程、函数

     

    一 视图

    视图是一个虚拟表(非真实存在),其本质是【根据SQL语句获取动态的数据集,并为其命名】,用户使用时只需使用【名称】即可获取结果集,可以将该结果集当做表来使用。

    使用视图我们可以把查询过程中的临时表摘出来,用视图去实现,这样以后再想操作该临时表的数据时就无需重写复杂的sql了,直接去视图中查找即可,但视图有明显地效率问题,并且视图是存放在数据库中的,如果我们程序中使用的sql过分依赖数据库中的视图,即强耦合,那就意味着扩展sql极为不便,因此并不推荐使用

    #两张有关系的表
    mysql> select * from course;
    +-----+--------+------------+
    | cid | cname  | teacher_id |
    +-----+--------+------------+
    |   1 | 生物   |          1 |
    |   2 | 物理   |          2 |
    |   3 | 体育   |          3 |
    |   4 | 美术   |          2 |
    +-----+--------+------------+
    4 rows in set (0.00 sec)
    
    mysql> select * from teacher;
    +-----+-----------------+
    | tid | tname           |
    +-----+-----------------+
    |   1 | 张磊老师        |
    |   2 | 李平老师        |
    |   3 | 刘海燕老师      |
    |   4 | 朱云海老师      |
    |   5 | 李杰老师        |
    +-----+-----------------+
    5 rows in set (0.00 sec)
    
    #查询李平老师教授的课程名
    mysql> select cname from course where teacher_id = (select tid from teacher where tname='李平老师');
    +--------+
    | cname  |
    +--------+
    | 物理   |
    | 美术   |
    +--------+
    2 rows in set (0.00 sec)
    
    #子查询出临时表,作为teacher_id等判断依据
    select tid from teacher where tname='李平老师'
    复制代码
    临时表应用举例

    一 创建视图

    #语法:CREATE VIEW 视图名称 AS  SQL语句
    create view teacher_view as select tid from teacher where tname='李平老师';
    
    #于是查询李平老师教授的课程名的sql可以改写为
    mysql> select cname from course where teacher_id = (select tid from teacher_view);
    +--------+
    | cname  |
    +--------+
    | 物理   |
    | 美术   |
    +--------+
    2 rows in set (0.00 sec)
    
    #!!!注意注意注意:
    #1. 使用视图以后就无需每次都重写子查询的sql,但是这么效率并不高,还不如我们写子查询的效率高
    
    #2. 而且有一个致命的问题:视图是存放到数据库里的,如果我们程序中的sql过分依赖于数据库中存放的视图,那么意味着,一旦sql需要修改且涉及到视图的部分,则必须去数据库中进行修改,而通常在公司中数据库有专门的DBA负责,你要想完成修改,必须付出大量的沟通成本DBA可能才会帮你完成修改,极其地不方便
    复制代码
    View Code

    二 使用视图

    #修改视图,原始表也跟着改
    mysql> select * from course;
    +-----+--------+------------+
    | cid | cname  | teacher_id |
    +-----+--------+------------+
    |   1 | 生物   |          1 |
    |   2 | 物理   |          2 |
    |   3 | 体育   |          3 |
    |   4 | 美术   |          2 |
    +-----+--------+------------+
    4 rows in set (0.00 sec)
    
    mysql> create view course_view as select * from course; #创建表course的视图
    Query OK, 0 rows affected (0.52 sec)
    
    mysql> select * from course_view;
    +-----+--------+------------+
    | cid | cname  | teacher_id |
    +-----+--------+------------+
    |   1 | 生物   |          1 |
    |   2 | 物理   |          2 |
    |   3 | 体育   |          3 |
    |   4 | 美术   |          2 |
    +-----+--------+------------+
    4 rows in set (0.00 sec)
     
    mysql> update course_view set cname='xxx'; #更新视图中的数据
    Query OK, 4 rows affected (0.04 sec)
    Rows matched: 4  Changed: 4  Warnings: 0
    
    mysql> insert into course_view values(5,'yyy',2); #往视图中插入数据
    Query OK, 1 row affected (0.03 sec)
    
    mysql> select * from course; #发现原始表的记录也跟着修改了
    +-----+-------+------------+
    | cid | cname | teacher_id |
    +-----+-------+------------+
    |   1 | xxx   |          1 |
    |   2 | xxx   |          2 |
    |   3 | xxx   |          3 |
    |   4 | xxx   |          2 |
    |   5 | yyy   |          2 |
    +-----+-------+------------+
    5 rows in set (0.00 sec)
    复制代码
    View Code

    我们不应该修改视图中的记录,而且在涉及多个表的情况下是根本无法修改视图中的记录的,如下图

    三 修改视图

    语法:ALTER VIEW 视图名称 AS SQL语句
    mysql> alter view teacher_view as select * from course where cid>3;
    Query OK, 0 rows affected (0.04 sec)
    
    mysql> select * from teacher_view;
    +-----+-------+------------+
    | cid | cname | teacher_id |
    +-----+-------+------------+
    |   4 | xxx   |          2 |
    |   5 | yyy   |          2 |
    +-----+-------+------------+
    2 rows in set (0.00 sec)
    复制代码
    View Code

    四 删除视图

    语法:DROP VIEW 视图名称
    
    DROP VIEW teacher_view
    View Code

    二 触发器

    使用触发器可以定制用户对表进行【增、删、改】操作时前后的行为,注意:没有查询

    一 创建触发器

    # 插入前
    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
    );
    
    #创建触发器
    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 |
    +----+-----------------+---------------------+
    2 rows in set (0.00 sec)
    复制代码
    View Code

    特别的:NEW表示即将插入的数据行,OLD表示即将删除的数据行。

    二 使用触发器

    触发器无法由用户直接调用,而知由于对表的【增/删/改】操作被动引发的。

    三 删除触发器

    drop trigger tri_after_insert_cmd;
    View Code

    三 事务

    事务用于将某些操作的多个SQL作为原子性操作,一旦有某一个出现错误,即可回滚到原来的状态,从而保证数据库数据完整性。

    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 |
    +----+------+---------+
    3 rows in set (0.00 sec)
    复制代码
    View Code

    四 存储过程

    一 介绍

    存储过程包含了一系列可执行的sql语句,存储过程存放于MySQL中,通过调用它的名字可以执行其内部的一堆sql

    使用存储过程的优点:

    #1. 用于替代程序写的SQL语句,实现程序与sql解耦
    
    #2. 基于网络传输,传别名的数据量小,而直接传sql数据量大

    使用存储过程的缺点:

    #1. 执行效率低
    
    #2. 程序员扩展功能不方便

    补充:程序与数据库结合使用的三种方式

    #方式一:
        MySQL:存储过程
        程序:调用存储过程
    
    #方式二:
        MySQL:
        程序:纯SQL语句
    
    #方式三:
        MySQL:
        程序:类和对象,即ORM(本质还是纯SQL语句)

    二 创建简单存储过程(无参)

    delimiter //
    create procedure p1()
    BEGIN
        select * from blog;
        INSERT into blog(name,sub_time) values("xxx",now());
    END //
    delimiter ;
    
    #在mysql中调用
    call p1() 
    
    #在python中基于pymysql调用
    cursor.callproc('p1') 
    print(cursor.fetchall())
    View Code

    三 创建存储过程(有参)

    对于存储过程,可以接收参数,其参数有三类:
    
    #in          仅用于传入参数用
    #out        仅用于返回值用
    #inout     既可以传入又可以当作返回值
    delimiter //
    create procedure p2(
        in n1 int,
        in n2 int
    )
    BEGIN
        
        select * from blog where id > n1;
    END //
    delimiter ;
    
    #在mysql中调用
    call p2(3,2)
    
    #在python中基于pymysql调用
    cursor.callproc('p2',(3,2))
    print(cursor.fetchall()
    in 传入参数
    delimiter //
    create procedure p3(
        in n1 int,
        out res int
    )
    BEGIN
        select * from blog where id > n1;
        set res = 1;
    END //
    delimiter ;
    
    #在mysql中调用
    set @res=0; #0代表假(执行失败),1代表真(执行成功)
    call p3(3,@res);
    select @res;
    
    #在python中基于pymysql调用
    cursor.callproc('p3',(3,0)) #0相当于set @res=0
    print(cursor.fetchall()) #查询select的查询结果
    
    cursor.execute('select @_p3_0,@_p3_1;') #@p3_0代表第一个参数,@p3_1代表第二个参数,即返回值
    print(cursor.fetchall())
    out 返回值
    delimiter //
    create procedure p4(
        inout n1 int
    )
    BEGIN
        select * from blog where id > n1;
        set n1 = 1;
    END //
    delimiter ;
    
    #在mysql中调用
    set @x=3;
    call p4(@x);
    select @x;
    
    
    #在python中基于pymysql调用
    cursor.callproc('p4',(3,))
    print(cursor.fetchall()) #查询select的查询结果
    
    cursor.execute('select @_p4_0;') 
    print(cursor.fetchall())
    inout 既可以传入又可以返回
    #介绍
    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中调用存储过程
    set @res=123;
    call p5(@res);
    select @res;
    
    #在python中基于pymysql调用存储过程
    cursor.callproc('p5',(123,))
    print(cursor.fetchall()) #查询select的查询结果
    
    cursor.execute('select @_p5_0;')
    print(cursor.fetchall())
    事务

    四 执行存储过程

    -- 无参数
    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)
    
    执行存储过程
    在mysql中执行存储过程
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import pymysql
    
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    # 执行存储过程
    cursor.callproc('p1', args=(1, 22, 3, 4))
    # 获取执行完存储的参数
    cursor.execute("select @_p1_0,@_p1_1,@_p1_2,@_p1_3")
    result = cursor.fetchall()
    
    conn.commit()
    cursor.close()
    conn.close()
    
    
    print(result)
    在python中基于pymysql执行存储过程

    五 删除存储过程

    drop procedure proc_name;
    View Code

    五 函数

    MySQL中提供了许多内置函数,例如:

    复制代码
    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'
    
    部分内置函数
    View Code
    复制代码
    #1 基本使用
    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 |
    +-------------------------------+----------+
    3 rows in set (0.00 sec)
    需要掌握的函数 data-format

    一 自定义函数

    #!!!注意!!!
    #函数中不要写sql语句(否则会报错),函数仅仅只是一个功能,是一个在sql中被应用的功能
    #若要想在begin...end...中写sql,请用存储过程
    delimiter //
    create function f1(
        i1 int,
        i2 int)
    returns int
    BEGIN
        declare num int;
        set num = i1 + i2;
        return(num);
    END //
    delimiter ;
    View Code
    delimiter //
    create function f5(
        i int
    )
    returns int
    begin
        declare res int default 0;
        if i = 10 then
            set res=100;
        elseif i = 20 then
            set res=200;
        elseif i = 30 then
            set res=300;
        else
            set res=400;
        end if;
        return res;
    end //
    delimiter ;
    View Code

    二 删除函数

    drop function func_name;
    View Code

    三 执行函数

    # 获取返回值
    select UPPER('egon') into @res;
    SELECT @res;
    
    
    # 在查询中使用
    select f1(11,nid) ,name from tb2;
    View Code

    六 流程控制

    一 条件语句

    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 条件语句

    二 循环语句

    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 ;
    while 循环
    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 ;
    repeat 循环
    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
    loop

     

     

  • 相关阅读:
    "上传"组件:<upload> —— 快应用组件库H-UI
    Xcode免证书调试
    iOS-OC-基本控件之UIPageControl
    关于装完系统出现a disk read error occurred的解决方法
    iOS-OC-基本控件之UITextField
    windows常用快捷键
    制作无广告启动盘
    自制垃圾批处理软件
    学习总结
    如何将BroadcastReceiver中的信息传到Activity中
  • 原文地址:https://www.cnblogs.com/liuchengdong/p/7481806.html
Copyright © 2011-2022 走看看