数据库之MySQL

目录

一、概述

二、安装

三、数据库操作

四、数据表 与 数据行 操作

  1、数据表 操作
  2、数据行 操作

五、视图

六、触发器

七、存储过程

八、函数

九、事务

十、索引

十一、其他

 

一、概述

1、什么是数据库 ?

答:数据的仓库

2、什么事SQL?
SQL是专为数据库而建立的操作命令集,是一种功能齐全的数据库语言。

3、都有哪些数据库
关系型数据库:sqllite,db2,oracle,access,sql server,MySQL
非关系型数据库:MongoDB,redis
 
ISAM:ISAM是一个定义明确且历经时间考验的数据表格管理方法,它在设计之时就考虑到数据库被查询的次数要远大于更新的次数。因此,ISAM执行读取操作的速度很快,而且不占用大量的内存和存储资源。ISAM的两个主要不足之处在于,它不支持事务处理,也不能够容错:如果你的硬盘崩溃了,那么数据文件就无法恢复了。如果你正在把ISAM用在关键任务应用程序里,那就必须经常备份你所有的实时数据,通过其复制特性,MYSQL能够支持这样的备份应用程序。


MyISAM:MyISAM是MySQL的ISAM扩展格式和缺省的数据库引擎。除了提供ISAM里所没有的索引和字段管理的大量功能,MyISAM还使用一种表格锁定的机制,来优化多个并发的读写操作,其代价是你需要经常运行OPTIMIZE TABLE命令,来恢复被更新机制所浪费的空间。MyISAM还有一些有用的扩展,例如用来修复数据库文件的MyISAMCHK工具和用来恢复浪费空间的 MyISAMPACK工具。MYISAM强调了快速读取操作,这可能就是为什么MySQL受到了WEB开发如此青睐的主要原因:在WEB开发中你所进行的大量数据操作都是读取操作。所以,大多数虚拟主机提供商和INTERNET平台提供商只允许使用MYISAM格式。MyISAM格式的一个重要缺陷就是不能在表损坏后恢复数据。


InnoDB:InnoDB数据库引擎都是造就MySQL灵活性的技术的直接产品,这项技术就是MYSQL+API。在使用MYSQL的时候,你所面对的每一个挑战几乎都源于ISAM和MyISAM数据库引擎不支持事务处理(transaction process)也不支持外来键。尽管要比ISAM和 MyISAM引擎慢很多,但是InnoDB包括了对事务处理和外来键的支持,这两点都是前两个引擎所没有的。如前所述,如果你的设计需要这些特性中的一者或者两者,那你就要被迫使用后两个引擎中的一个了。

MEMORY: MEMORY是MySQL中一类特殊的存储引擎。它使用存储在内存中的内容来创建表,而且数据全部放在内存中。这些特性与前面的两个很不同。每个基于MEMORY存储引擎的表实际对应一个磁盘文件。该文件的文件名与表名相同,类型为frm类型。该文件中只存储表的结构。而其数据文件,都是存储在内存中,这样有利于数据的快速处理,提高整个表的效率。值得注意的是,服务器需要有足够的内存来维持MEMORY存储引擎的表的使用。如果不需要了,可以释放内存,甚至删除不需要的表。MEMORY默认使用哈希索引。速度比使用B型树索引快。当然如果你想用B型树索引,可以在创建索引时指定。注意,MEMORY用到的很少,因为它是把数据存到内存中,如果内存出现异常就会影响数据。如果重启或者关机,所有数据都会消失。因此,基于MEMORY的表的生命周期很短,一般是一次性的。



在实际工作中,选择一个合适的存储引擎是一个比较复杂的问题。每种存储引擎都有自己的优缺点,不能笼统地说谁比谁好。

 

InnoDB:支持事务处理,支持外键,支持崩溃修复能力和并发控制。如果需要对事务的完整性要求比较高(比如银行),要求实现并发控制(比如售票),那选择InnoDB有很大的优势。如果需要频繁的更新、删除操作的数据库,也可以选择InnoDB,因为支持事务的提交(commit)和回滚(rollback)。 

MyISAM:插入数据快,空间和内存使用比较低。如果表主要是用于插入新记录和读出记录,那么选择MyISAM能实现处理高效率。如果应用的完整性、并发性要求比较低,也可以使用。

MEMORY:所有的数据都在内存中,数据的处理速度快,但是安全性不高。如果需要很快的读写速度,对数据的安全性要求较低,可以选择MEMOEY。它对表的大小有要求,不能建立太大的表。所以,这类数据库只使用在相对较小的数据库表。

注意,同一个数据库也可以使用多种存储引擎的表。如果一个表要求比较高的事务处理,可以选择InnoDB。这个数据库中可以将查询要求比较高的表选择MyISAM存储。如果该数据库需要一个用于查询的临时表,可以选择MEMORY存储引擎。
Mysql常用的三种数据库引擎比较

 

二、安装

想要使用MySQL来存储并操作数据,则需要做几件事情:
  a. 安装MySQL服务端
  b. 安装MySQL客户端
  b. 【客户端】连接【服务端】
  c. 【客户端】发送命令给【服务端MySQL】服务的接受命令并执行相应操作(增删改查等)

Window版本

        官网:http://dev.mysql.com/downloads/mysql/
        可执行文件
            。。。
        压缩包
            放置任意目录
            进入该目录
            
        初始化
            针对服务端:
                mysqld
                cmd命令:mysqld --initialize-insecure(可能需要在根目录创建data,看是否有报错信息)
                用户名:root 密码:空
                
                
            PS:我的win10得安装Microsoft.Visual.C++.2013.Redistributable.Package这个补丁包,说是有两个dll不存在。
            
        启动服务端:
            mysqld
            
        
        客户端连接
            登录:mysql -u root -p 
        
            发送指令:
                show databases;
                create database db1;
        
        环境变量的配置:
            path
        
        windows服务:
            mysqld --install  # 放到services.msc里面,可自启动
            mysqld --remove  # 从services.msc移除
            net start MySQL  # 服务启动
            net stop MySQL  # 服务停止
我的安装过程

附:可使用navicat客户端

 

Linux版本

安装:
yum install mysql-server

启动:
mysql.server start

客户端连接:
连接:
    mysql -h host -u user -p
 
    常见错误:
        ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2), it means that the MySQL server daemon (Unix) or service (Windows) is not running.
退出:
    QUIT 或者 Control+D
安装
第一步:安装从网上下载文件的wget命令

[root@master ~]# yum -y install wget
第二步:下载mysql的repo源

[root@master ~]# wget http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm 
第三步:安装mysql-community-release-el7-5.noarch.rpm包

[root@master ~]# rpm -ivh mysql-community-release-el7-5.noarch.rpm
第四步:查看下

[root@master ~]# ls -1 /etc/yum.repos.d/mysql-community*
/etc/yum.repos.d/mysql-community.repo
/etc/yum.repos.d/mysql-community-source.repo
会获得两个mysql的yum repo源:/etc/yum.repos.d/mysql-community.repo,/etc/yum.repos.d/mysql-community-source.repo。

第五步:安装mysql

[root@master ~]# yum install mysql-server
 
问题解决:centos7下解决yum install mysql-server没有可用包

 

三、数据库操作

1、显示数据库

1
SHOW DATABASES;

默认数据库:
  mysql - 用户权限相关数据
  test - 用于用户测试数据
  information_schema - MySQL本身架构相关数据

2、创建数据库

1
2
3
4
5
 

# 统一使用
CREATE DATABASE 数据库名称 DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;
 
# utf-8
CREATE DATABASE 数据库名称 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
 
# gbk
CREATE DATABASE 数据库名称 DEFAULT CHARACTER SET gbk COLLATE gbk_chinese_ci;

3、使用数据库

1
USE db_name;

显示当前使用的数据库中所有表:SHOW TABLES;

4、用户管理

1
2
3
4
5
6
7
8
9
10
创建用户
    create user '用户名'@'IP地址' identified by '密码';
删除用户
    drop user '用户名'@'IP地址';
修改用户
    rename user '用户名'@'IP地址'; to '新用户名'@'IP地址';;
修改密码
    set password for '用户名'@'IP地址' = Password('新密码')
  
PS:用户权限相关数据保存在mysql数据库的user表中,所以也可以直接对其进行操作(不建议)

5、授权管理

1
2
3
show grants for '用户'@'IP地址'                  -- 查看权限
grant  权限 on 数据库.表 to   '用户'@'IP地址'      -- 授权
revoke 权限 on 数据库.表 from '用户'@'IP地址'      -- 取消权限
all privileges  除grant外的所有权限
            select          仅查权限
            select,insert   查和插入权限
            ...
            usage                   无访问权限
            alter                   使用alter table
            alter routine           使用alter procedure和drop procedure
            create                  使用create table
            create routine          使用create procedure
            create temporary tables 使用create temporary tables
            create user             使用create user、drop user、rename user和revoke  all privileges
            create view             使用create view
            delete                  使用delete
            drop                    使用drop table
            execute                 使用call和存储过程
            file                    使用select into outfile 和 load data infile
            grant option            使用grant 和 revoke
            index                   使用index
            insert                  使用insert
            lock tables             使用lock table
            process                 使用show full processlist
            select                  使用select
            show databases          使用show databases
            show view               使用show view
            update                  使用update
            reload                  使用flush
            shutdown                使用mysqladmin shutdown(关闭MySQL)
            super                   􏱂􏰈使用change master、kill、logs、purge、master和set global。还允许mysqladmin􏵗􏵘􏲊􏲋调试登陆
            replication client      服务器位置的访问
            replication slave       由复制从属使用
对于权限
        对于目标数据库以及内部其他:
            数据库名.*           数据库中的所有
            数据库名.表          指定数据库中的某张表
            数据库名.存储过程     指定数据库中的存储过程
            *.*                所有数据库
对于数据库
            用户名@IP地址         用户只能在改IP下才能访问
            用户名@192.168.1.%   用户只能在改IP段下才能访问(通配符%表示任意)
            用户名@%             用户可以再任意IP下访问(默认IP地址为%)
对于用户和IP
grant all privileges on db1.tb1 TO '用户名'@'IP'

grant select on db1.* TO '用户名'@'IP'

grant select,insert on *.* TO '用户名'@'IP'

revoke select on db1.tb1 from '用户名'@'IP'
示例1
create user "alex"@"192.168.1.1" identified by "123123";

create user "alex"@"192.168.1.%" identified by "123123";

create user "alex"@"192.168.%" identified by "123123";

create user "alex"@"%" identified by "123123";
示例2 创建用户
grant 权限

grant select,insert,update on db1.t1 to "alex"@"%";

grant all privileges on db1.* to "alex"@"%";
示例3 授权

 

其他的:

1
flush privileges,将数据读取到内存中,从而立即生效。
# 启动免授权服务端
mysqld --skip-grant-tables

# 客户端
mysql -u root -p

# 修改用户名密码
update mysql.user set authentication_string=password('666') where user='root';
flush privileges;
忘记密码

 

alter user 'user'@;ip' identified with mysql_native_password by 'password';

flush privileges;


// 该用户可通过navicat链接了
Navicat连接Mysql报错:Client does not support authentication protocol requested by server;

 

 

四、数据表 与 数据行 操作

1、数据表 操作

(0)基本数据类型

bit[(M)]
            二进制位(101001),m表示二进制位的长度(1-64),默认m=1

        tinyint[(m)] [unsigned] [zerofill]

            小整数,数据类型用于保存一些范围的整数数值范围:
            有符号:
                -128 ~ 127.
            无符号:
~ 255

            特别的: MySQL中无布尔值,使用tinyint(1)构造。

        int[(m)][unsigned][zerofill]

            整数,数据类型用于保存一些范围的整数数值范围:
                有符号:
                    -2147483648 ~ 2147483647
                无符号:
~ 4294967295

            特别的:整数类型中的m仅用于显示,对存储范围无限制。例如: int(5),当插入数据2时,select 时数据显示为: 00002

        bigint[(m)][unsigned][zerofill]
            大整数,数据类型用于保存一些范围的整数数值范围:
                有符号:
                    -9223372036854775808 ~ 9223372036854775807
                无符号:
 ~  18446744073709551615

        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,
                    1.175494351E-38 to 3.402823466E+38
                有符号:
                    1.175494351E-38 to 3.402823466E+38

            **** 数值越大,越不准确 ****

        DOUBLE[(M,D)] [UNSIGNED] [ZEROFILL]
            双精度浮点数(非准确小数值),m是数字总个数,d是小数点后个数。

                无符号:
                    -1.7976931348623157E+308 to -2.2250738585072014E-308
                    2.2250738585072014E-308 to 1.7976931348623157E+308
                有符号:
                    2.2250738585072014E-308 to 1.7976931348623157E+308
            **** 数值越大,越不准确 ****


        char (m)
            char数据类型用于表示固定长度的字符串,可以包含最多达255个字符。其中m代表字符串的长度。
            PS: 即使数据小于m长度,也会占用m长度
        varchar(m)
            varchars数据类型用于变长的字符串,可以包含最多达255个字符。其中m代表该数据类型所允许保存的字符串的最大长度,只要长度小于该最大值的字符串都可以被保存在该数据类型中。

            注:虽然varchar使用起来较为灵活,但是从整个系统的性能角度来说,char数据类型的处理速度更快,有时甚至可以超出varchar处理速度的50%。因此,用户在设计数据库时应当综合考虑各方面的因素,以求达到最佳的平衡

        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
            枚举类型,
            An ENUM column can have a maximum of 65,535 distinct elements. (The practical limit is less than 3000.)
            示例:
                CREATE TABLE shirts (
                    name VARCHAR(40),
                    size ENUM('x-small', 'small', 'medium', 'large', 'x-large')
                );
                INSERT INTO shirts (name, size) VALUES ('dress shirt','large'), ('t-shirt','medium'),('polo shirt','small');

        set
            集合类型
            A SET column can have a maximum of 64 distinct members.
            示例:
                CREATE TABLE myset (col SET('a', 'b', 'c', 'd'));
                INSERT INTO myset (col) VALUES ('a,d'), ('d,a'), ('a,d,a'), ('a,d,d'), ('d,a,d');

        DATE
            YYYY-MM-DD(1000-01-01/9999-12-31)

        TIME
            HH:MM:SS('-838:59:59'/'838:59:59')

        YEAR
            YYYY(1901/2155)

        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 年某时)
基本数据类型 大致分为:数值、时间和字符串

更多参考:

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

(1)增

创建表:

1
2
3
4
create table 表名(
    列名  类型  是否可以为空,
    列名  类型  是否可以为空
)ENGINE=InnoDB DEFAULT CHARSET=utf8

参数说明:

       是否可空,null表示空,非字符串
            not null    - 不可空
            null        - 可空
是否可以为空
        默认值,创建列时可以指定默认值,当插入数据时如果未主动设置,则自动添加默认值
            create table tb1(
                nid int not null defalut 2,
                num int not null
            )
默认值
自增,如果为某列设置自增列,插入数据时无需设置此列,默认将自增(表中只能有一个自增列)
            create table tb1(
                nid int not null auto_increment primary key,
                num int null
            )
            或
            create table tb1(
                nid int not null auto_increment,
                num int null,
                index(nid)
            )
            注意:1、对于自增列,必须是索引(含主键)。
                 2、对于自增可以设置步长和起始值
                     show session variables like 'auto_inc%';
                     set session auto_increment_increment=2;
                     set session auto_increment_offset=10;

                     shwo global  variables like 'auto_inc%';
                     set global auto_increment_increment=2;
                     set global auto_increment_offset=10;
自增
主键,一种特殊的唯一索引,不允许有空值,如果主键使用单个列,则它的值必须唯一,如果是多列,则其组合必须唯一。
            create table tb1(
                nid int not null auto_increment primary key,
                num int null
            )
            或
            create table tb1(
                nid int not null,
                num int not null,
                primary key(nid,num)
            )
主键
外键,一个特殊的索引,只能是指定内容
            creat table color(
                nid int not null primary key,
                name char(16) not null
            )

            create table fruit(
                nid int not null primary key,
                smt char(32) null ,
                color_id int not null,
                constraint fk_cc foreign key (color_id) references color(nid)
            )
外键

 

(2)删

删除表

1
drop table 表名

清空表

1
2
delete from 表名
truncate table 表名

(3)改

修改表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
添加列:alter table 表名 add 列名 类型
删除列:alter table 表名 drop column 列名
修改列:
        alter table 表名 modify column 列名 类型;  -- 类型
        alter table 表名 change 原列名 新列名 类型; -- 列名,类型
  
添加主键:
        alter table 表名 add primary key(列名);
删除主键:
        alter table 表名 drop primary key;
        alter table 表名  modify  列名 int, drop primary key;
  
添加外键:alter table 从表 add constraint 外键名称(形如:FK_从表_主表) foreign key 从表(外键字段) references 主表(主键字段);
删除外键:alter table 表名 drop foreign key 外键名称
  
修改默认值:ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;
删除默认值:ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;

2、数据行 操作

1、增

1
2
3
insert into 表 (列名,列名...) values (值,值,值...)
insert into 表 (列名,列名...) values (值,值,值...),(值,值,值...)
insert into 表 (列名,列名...) select (列名,列名...) from 

2、删

1
2
delete from 
delete from 表 where id=1 and name'alex'

3、改

1
update 表 set name = 'alex' where id>1

4、查

1
2
3
select from 
select from 表 where id > 1
select nid,name,gender as gg from 表 where id > 1

5、其他

a、条件
    select * from 表 where id > 1 and name != 'alex' and num = 12;
 
    select * from 表 where id between 5 and 16;
 
    select * from 表 where id in (11,22,33)
    select * from 表 where id not in (11,22,33)
    select * from 表 where id in (select nid from 表)
 
b、通配符
    select * from 表 where name like 'ale%'  - ale开头的所有(多个字符串)
    select * from 表 where name like 'ale_'  - ale开头的所有(一个字符)
 
c、限制
    select * from 表 limit 5;            - 前5行
    select * from 表 limit 4,5;          - 从第4行开始的5行
    select * from 表 limit 5 offset 4    - 从第4行开始的5行
 
d、排序
    select * from 表 order by 列 asc              - 根据 “列” 从小到大排列
    select * from 表 order by 列 desc             - 根据 “列” 从大到小排列
    select * from 表 order by 列1 desc,列2 asc    - 根据 “列1” 从大到小排列,如果相同则按列2从小到大排序
 
e、分组
    select num from 表 group by num
    select num,nid from 表 group by num,nid
    select num,nid from 表  where nid > 10 group by num,nid order nid desc
    select num,nid,count(*),sum(score),max(score),min(score) from 表 group by num,nid
 
    select num from 表 group by num having max(id) > 10
 
    特别的:group by 必须在where之后,order by之前
 
f、连表
    无对应关系则不显示
    select A.num, A.name, B.name
    from A,B
    Where A.nid = B.nid
 
    无对应关系则不显示
    select A.num, A.name, B.name
    from A inner join B
    on A.nid = B.nid
 
    A表所有显示,如果B中无对应关系,则值为null
    select A.num, A.name, B.name
    from A left join B
    on A.nid = B.nid
 
    B表所有显示,如果B中无对应关系,则值为null
    select A.num, A.name, B.name
    from A right join B
    on A.nid = B.nid
 
g、组合
    组合,自动处理重合
    select nickname
    from A
    union
    select name
    from B
 
    组合,不处理重合
    select nickname
    from A
    union all
    select name
    from B
排序、分组、通配符、连表 等

 

五、视图

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

SELECT
    *
FROM
    (
        SELECT
            nid,
            NAME
        FROM
            tb1
        WHERE
            nid > 2
    ) AS A
WHERE
    A. NAME > 'alex';
临时表搜索
--格式:CREATE VIEW 视图名称 AS  SQL语句
CREATE VIEW v1 AS 
SELET nid, 
    name
FROM
    A
WHERE
    nid > 4
创建视图
--格式:DROP VIEW 视图名称

DROP VIEW v1
删除视图
-- 格式:ALTER VIEW 视图名称 AS SQL语句

ALTER VIEW v1 AS
SELET A.nid,
    B. NAME
FROM
    A
LEFT JOIN B ON A.id = B.nid
LEFT JOIN C ON A.id = C.nid
WHERE
    A.id > 2
AND C.nid < 5
修改视图
select * from v1
使用视图

使用视图时,将其当作表进行操作即可,由于视图是虚拟表,所以无法使用其对真实表进行创建、更新和删除操作,仅能做查询用。

六、触发器

对某个表进行【增/删/改】操作的前后如果希望触发某个特定的行为时,可以使用触发器,触发器用于定制用户对表的行进行【增/删/改】前后的行为。

1、创建基本语法

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

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

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

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

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

# 更新后
CREATE TRIGGER tri_after_update_tb1 AFTER UPDATE ON tb1 FOR EACH ROW
BEGIN
    ...
END
语法
delimiter //
CREATE TRIGGER tri_before_insert_tb1 BEFORE INSERT ON tb1 FOR EACH ROW
BEGIN

IF NEW. NAME == 'alex' THEN
    INSERT INTO tb2 (NAME)
VALUES
    ('aa')
END
END//
delimiter ;
插入前触发器
delimiter //
CREATE TRIGGER tri_after_insert_tb1 AFTER INSERT ON tb1 FOR EACH ROW
BEGIN
    IF NEW. num = 666 THEN
        INSERT INTO tb2 (NAME)
        VALUES
            ('666'),
            ('666') ;
    ELSEIF NEW. num = 555 THEN
        INSERT INTO tb2 (NAME)
        VALUES
            ('555'),
            ('555') ;
    END IF;
END//
delimiter ;
插入后触发器

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

2、删除触发器

DROP TRIGGER tri_after_insert_tb1;
删除触发器

3、使用触发器

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

insert into tb1(num) values(666)
使用触发器

 

七、存储过程

 存储过程是一个SQL语句集合,当主动去调用存储过程时,其中内部的SQL语句会按照逻辑执行。

1、创建存储过程

-- 创建存储过程

delimiter //
create procedure p1()
BEGIN
    select * from t1;
END//
delimiter ;



-- 执行存储过程

call p1()
无参数存储过程

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

  • in          仅用于传入参数用
  • out        仅用于返回值用
  • inout     既可以传入又可以当作返回值
-- 创建存储过程
delimiter \\
create procedure p1(
    in i1 int,
    in i2 int,
    inout i3 int,
    out r1 int
)
BEGIN
    DECLARE temp1 int;
    DECLARE temp2 int default 0;
    
    set temp1 = 1;

    set r1 = i1 + i2 + temp1 + temp2;
    
    set i3 = i3 + 100;

end\\
delimiter ;

-- 执行存储过程
set @t1 =4;
set @t2 = 0;
CALL p1 (1, 2 ,@t1, @t2);
SELECT @t1,@t2;
有参数的存储过程
delimiter //
                    create procedure p1()
                    begin
                        select * from v1;
                    end //
                    delimiter ;
1. 结果集
delimiter //
                    create procedure p2(
                        in n1 int,
                        inout n3 int,
                        out n2 int,
                    )
                    begin
                        declare temp1 int ;
                        declare temp2 int default 0;

                        select * from v1;
                        set n2 = n1 + 100;
                        set n3 = n3 + n1 + 100;
                    end //
                    delimiter ;
2. 结果集+out值
delimiter \\
                        create PROCEDURE p1(
                            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 tb2(name)values('seven');
                          COMMIT; 
                         
                          -- SUCCESS 
                          set p_return_code = 0; 
                         
                          END\\
                    delimiter ;
3. 事务
delimiter //
                    create procedure p3()
                    begin 
                        declare ssid int; -- 自定义变量1  
                        declare ssname varchar(50); -- 自定义变量2  
                        DECLARE done INT DEFAULT FALSE;


                        DECLARE my_cursor CURSOR FOR select sid,sname from student;
                        DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
                        
                        open my_cursor;
                            xxoo: LOOP
                                fetch my_cursor into ssid,ssname;
                                if done then 
                                    leave xxoo;
                                END IF;
                                insert into teacher(tname) values(ssname);
                            end loop xxoo;
                        close my_cursor;
                    end  //
                    delimter ;
4. 游标
delimiter \\
                    CREATE PROCEDURE p4 (
                        in nid int
                    )
                    BEGIN
                        PREPARE prod FROM 'select * from student where sid > ?';
                        EXECUTE prod USING @nid;
                        DEALLOCATE prepare prod; 
                    END\\
                    delimiter ;
5. 动态执行SQL

2、删除存储过程

drop procedure proc_name;
删除存储过程

3、执行存储过程

-- 无参数
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)
执行存储过程
#!/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)
pymysql执行存储过程

 

八、函数

 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'

部分内置函数
部分内置函数

更多函数:中文猛击这里 OR 官方猛击这里

delimiter \\
create function f1(
    i1 int,
    i2 int)
returns int
BEGIN
    declare num int;
    set num = i1 + i2;
    return(num);
END \\
delimiter ;
自定义函数
drop function func_name;
删除函数
# 获取返回值
declare @i VARCHAR(32);
select UPPER('alex') into @i;
SELECT @i;


# 在查询中使用
select f1(11,nid) ,name from tb2;
执行函数

 

九、事务

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

delimiter \\
create PROCEDURE p1(
    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 tb2(name)values('seven');
  COMMIT; 
 
  -- SUCCESS 
  set p_return_code = 0; 
 
  END\\
delimiter ;
支持事务的存储过程
set @i =0;
call p1(@i);
select @i;

 

十、索引

索引,是数据库中专门用于帮助用户快速查询数据的一种数据结构。类似于字典中的目录,查找字典内容时可以根据目录查找到数据的存放位置,然后直接获取即可。

1
2
3
4
5
6
7
                    30
 
        10                        40
 
   5         15            35             66
 
1   6     11    19      21      39     55     100

MySQL中常见索引有:

  • 普通索引
  • 唯一索引
  • 主键索引
  • 组合索引

补充:https://www.cnblogs.com/fat39/p/10109593.html

1、普通索引

普通索引仅有一个功能:加速查询

create table in1(
    nid int not null auto_increment primary key,
    name varchar(32) not null,
    email varchar(64) not null,
    extra text,
    index ix_name (name)
)
创建表 + 索引
create index index_name on table_name(column_name)
创建索引
drop index_name on table_name;
删除索引
show index from table_name;
查看索引

注意:对于创建索引时如果是BLOB 和 TEXT 类型,必须指定length。

create index ix_extra on in1(extra(32));

2、唯一索引

唯一索引有两个功能:加速查询 和 唯一约束(可含null)

create table in1(
    nid int not null auto_increment primary key,
    name varchar(32) not null,
    email varchar(64) not null,
    extra text,
    unique ix_name (name)
)
创建表 + 唯一索引
create unique index 索引名 on 表名(列名)
创建唯一索引
drop unique index 索引名 on 表名
删除唯一索引

3、主键索引

主键有两个功能:加速查询 和 唯一约束(不可含null)

create table in1(
    nid int not null auto_increment primary key,
    name varchar(32) not null,
    email varchar(64) not null,
    extra text,
    index ix_name (name)
)

OR

create table in1(
    nid int not null auto_increment,
    name varchar(32) not null,
    email varchar(64) not null,
    extra text,
    primary key(ni1),
    index ix_name (name)
)
创建表 + 创建主键
alter table 表名 add primary key(列名);
创建主键
alter table 表名 drop primary key;
alter table 表名  modify  列名 int, drop primary key;
删除主键

4、组合索引

组合索引是将n个列组合成一个索引

其应用场景为:频繁的同时使用n列来进行查询,如:where n1 = 'alex' and n2 = 666。

create table in3(
    nid int not null auto_increment primary key,
    name varchar(32) not null,
    email varchar(64) not null,
    extra text
)
创建表
create index ix_name_email on in3(name,email);
创建组合索引

如上创建组合索引之后,查询:

  • name and email  -- 使用索引
  • name                 -- 使用索引
  • email                 -- 不使用索引

注意:对于同时搜索n个条件时,组合索引的性能好于多个单一索引合并。

 

十一、其他

 1、条件语句

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

2、循环语句

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

3、动态执行SQL语句

delimiter \\
DROP PROCEDURE IF EXISTS proc_sql \\
CREATE PROCEDURE proc_sql ()
BEGIN
    declare p1 int;
    set p1 = 11;
    set @p1 = p1;

    PREPARE prod FROM 'select * from tb2 where nid > ?';
    EXECUTE prod USING @p1;
    DEALLOCATE prepare prod; 

END\\
delimiter ;
动态执行SQL

补充

 区分大小写

 

 

参考or转发:

http://www.cnblogs.com/wupeiqi/articles/5713315.html

http://www.cnblogs.com/wupeiqi/articles/5713323.html

附:

数据库
    MySQL:是用于管理文件的一个软件
        - 服务端软件
            -socket服务端
            -本地文件操作
            -解析指令【SQL语句】
        - 客户端软件(各种各样)
            -socket客户端
            -发送指令
            -解析指令【SQL语句】
            
        PS:
            -DBMS数据库管理系统
            -SQL语句
        
    技能
        -安装 服务端和客户端
        -连接
        -学习SQL语句规则;指示服务端做任意操作
        -
    
    其他类似软件:
        关系型数据库:sqllite,db2,oracle,access,sql server,MySQL
        非关系型数据库:MongoDB,redis

        
1.MySQL安装
    Windows:
        官网:http://dev.mysql.com/downloads/mysql/
        可执行文件
            。。。
        压缩包
            放置任意目录
            初始化
                针对服务端:
                    mysqld
                    cmd命令:mysqld --initialize-insecure(可能需要在根目录创建data,看是否有报错信息)
                    用户名:root 密码:空
                    
                    
                PS:我的win10得安装Microsoft.Visual.C++.2013.Redistributable.Package这个补丁包,说是有两个dll不存在。
            启动服务端:
                mysqld
                
            
            客户端连接
                登录:mysql -u root -p 
            
                发送指令:
                    show databases;
                    create database db1;
            
            环境变量的配置:
                path
            
            windows服务:
                mysqld --install  # 放到services.msc里面,可自启动
                mysqld --remove  # 从services.msc移除
                net start MySQL  # 服务启动
                net stop MySQL  # 服务停止

2、关于连接
    文件夹【数据库】
        文件夹【表】
            数据行【行】
            数据行
    连接:
        show databases;
        use 数据库名称;
        show tables;
        select * from 表名称;
        select name,age,id from 表名称;
        mysql数据库user表
        use mysql;
        select user,host from user;
        
        
        
        默认:用户root
        创建用户:
            create user "alex"@"192.168.1.1" identified by "123123";
            create user "alex"@"192.168.1.%" identified by "123123";
            create user "alex"@"192.168.%" identified by "123123";
            create user "alex"@"%" identified by "123123";
        授权:
            权限  人
            
            grant 权限
            grant select,insert,update on db1.t1 to "alex"@"%";
            grant all privileges on db1.* to "alex"@"%";
            
                
        
3.学习SQL语句规则
    操作文件夹(数据库)
        create database db2;
        create database db2 default charset utf8;
        show databases;
        drop database db2;
        
    操作文件(表)
        show tables;
        create table t1(id int,name char(10)) default charset=utf8;
        create table t1(id int,name char(10)) engine=innodb default charset=utf8;
        create table t1(
            列名 类型 null,
            列名 类型 not null,
            列名 类型 not null default 1,
            列名 类型 not null auto_increment primary key,
            id int,
            name char(10)
        )

        
        
        # innodb 支持事务,原子性操作
        # myisam 
        auto_increment:自增
        primary key:约束(不能重复、不能为空);加速查找
        not null:是否为空
        数据类型:
            数字:
                tinyint
                int
                bigint
                
                FLOAT
                DOUBLE
                DECIMAL(精准的)
            字符串:
                char(10)    速度快
                    root(占10个)
                varchar(10)
                    root(仅占4个,节省空间)
                ps:创建数据表时把定长的往数据表前面放
                
                text
                
                上传文件:
                    文件存硬盘
                    db存路径
            
            时间类型:
                DATETIME
        
        create table t1(
            id int not null auto_increment primary key,
            num decimal(10,5),
            name char(10)
        )engine=innodb default charset=utf8;
        
        
        
            枚举
        create table shirts(
            name varchar(40);
            size ENUM("XL","L","M","s")  # 枚举
        );
        insert into shirts(name,size) values("afd","XL"),("bcd","M");
        
            组合(少)
        create table shirts(
            name varchar(40);
            size SET("a","b","c","d")  # 枚举
        );
        insert into shirts(name,size) values("afd","a"),("bcd","a","b","c");
        
        清空表:
            delete from t1;
            truncate table t1;

        删除表:
            drop table t1;
        
        查看table
            desc table_name
            show create table table_name \G;  # 查看创建table的语句
    
    
    
    操作文件中的内容:
        插入数据:
            insert into t1(id,name) values(1,"fat39");
        删除:
            delete from t1 where id<6;
        修改:
            update t1 set age=18;
            update t1 set age=18 where age=17;
        查看数据:
            select * from t1;
    
    外键:
        create table userinfo(
            uid bigint auto_increment primary key,
            name varchar(32),
            department_id int,
            constraint fk_user_depar foreign key (department_id) references department(id),
            constraint fk_xx_ff foreign key (xx_id) references xx(id)
        )engine=innodb default charset=utf8;
        
        create table department(
            id bigint auto_increment primary key,
            title char(15)
        )engine=innodb default charset=utf8;

    
    补充:
    主键:
        一张表只有一个主键;
        一个主键可以由多个列组成
        create table t1(
        id1...
        id2...
        name...
        num ...
        primary key (id1,id2)
        )
    
        
    外键:
        create table department(
            id1 bigint auto_increment primary key,
            id2 bigint auto_increment,
            title char(15)
        )engine=innodb default charset=utf8;
        
        外键名唯一,不能重复
        create table userinfo(
            uid bigint auto_increment primary key,
            name varchar(32),
            department_id int,
            d_id int,
            constraint fk_user_depar foreign key (department_id,d_id) references department(id1,id2),
        )engine=innodb default charset=utf8;

    

    
    
    对于自增:

        
        desc table_name;
        show create table table_name;
        show create table table_name \G;
        alter table t10 set AUTO_INCREMENT=20;

        
        mysql:自增步长
            基于会话级别:
                show session variables like "auto_inc%";    #查看会话变量
                set session auto_increment_increment=2;     #设置会话步长
                set session auto_increment_offset=10;
            基于全局级别:
                show global variables like "auto_inc%";    # 查看全局变量;
                set global auto_increment_increment=2      # 设置会话步长
                set global auto_increment_offset=10;
        
            清零
            1、清空表时使用truncate命令,而不用delete命令
                truncate test;
            2、alter table table_name auto_increment=1;
            
            
        
        SQLserver:自增步长:
            基于表级别:
            Create Table: CREATE TABLE `class` (
                `cid` int(11) NOT NULL AUTO_INCREMENT,
                `caption` varchar(32) NOT NULL,
                PRIMARY KEY (`cid`)
            ) ENGINE=InnoDB AUTO_INCREMENT=4,步长=20DEFAULT CHARSET=utf8

        
        

第二天内容:
    0、唯一索引
        create table t1(
            id int ...,
            num int ...,
            xx int,
            unique uq1 (num)  # 单列唯一
            unique uq1 (num,xx)  # 联合唯一,不同同时相同
        )
        PS:
            唯一索引:
                约束不能重复(可以为空)
                PS:主键不能重复(不能为空)
            加速查找
                
    1、外键的变种
        a、用户表和部门表
            用户:
                1 Alex 1
                2 root 1
                3 egon 2
                4 laoyao 3
            部门:
                1、服务
                2、报告
                3、公关
            ==》一对多
            
        b、用户表和博客表
            用户表:
                1 alex
                2 root
                3 egon
                4 laoyao
            博客表
                idx url FK()+唯一
                1 /yuanchenqi/ 4
                2 /alex3714/ 1
                3 /asdfa/ 3
                4 /adsfasdf/ 2
            ==》一对一
        '
        c、用户表
            示例一:(百合网)  相亲记录表
                用户表
                相亲表
            示例二:
                用户表
                主机表
                用户主机关系表

            
            ==》多对多
        
            create table student(
            id int not null auto_increment primary key,
            gender enum("F","M"),
            name varchar(32)
            )engine=innodb default charset=utf8;



            create table pc(
            id int not null auto_increment primary key,
            device varchar(32)
            )engine=innodb default charset=utf8;

            create table relation_s_p(
            id int not null auto_increment primary key,
            user int not null,
            hostid int not null,
            unique uni_user_host (user,hostid),
            constraint fk_rela_st foreign key (user) references student(id),
            constraint fk_rela_pc foreign key (hostid) references pc(id)
            )engine=innodb default charset=utf8;
        
    2、SQL语句数据行操作补充
        增
            insert into tb1(name,age) values("alex",12);
            insert into tb1(name,age) values("alex",12),("root",18);
            insert into tb2(name,age) select name,age from tb1;
        删
            delete from tb2;
            delete from tb2 where id != 2;
            delete from tb2 where id != 2 and name = "alex";
            delete from tb2 where id != 2 or name = "alex";
        改
            update tb2 set name="alex" where id>12 and name="xx";
            update tb2 set name="alex",age=19 where id>12 and name="xx";
        查
            select * from tb2;
            select id,name from tb2;
            select id,name from tb2 where id > 10 or name = "xxx";
            select id,name as cname from tb2 where id > 10 or name = "xxx";
            select name,age,1 from tb2;
            其他:
                select * from tb2 where id <> 1;
                select * from tb2 where id in (1,5,12);
                select * from tb2 where id in (select id from table_name)
                select * from tb2 where id not in (1,5,12);
                select * from tb2 where id between 1 and 3;   # 两边都是闭区间  1<=    >=3
                select * from tb2 where name like "a%";  # a%:以a开头,%a:以a结尾;
                select * from tb2 where name like "a_";
                
                select * from tb2 limit 10;    # 查看前10条
                select * from tb2 limit 0,10;    # 查看0-10条
                select * from tb2 limit 20,10;    # 起始位置:20,查看10条
                select * from tb2 limit 10 offset 20;  # 同上
                
                排序:
                    select * from tb2 order by id desc;  # 大到小
                    select * from tb2 order by id asc;   # 小到大
                    select * from tb2 order by id asc,name asc;   # 排2列
                    
                    取后10条数据
                    select * from tb2 order by id desc limit 10;
                
                分组:
                    select count(id),max(id),part_id from tb2 group by part_id;
                    
                    count
                    max
                    min
                    sum
                    avg
                    
                    ****** 如果对于聚合函数结果进行二次筛选,必须使用having ******
                    select count(id),part_id from tb2 group by part_id having count(id) > 1;
                    
                    
                连表操作:(最重要的)
                    select * from userinfo,password where userinfo.id = password.user_id;
                    select * from userinfo left join password on userinfo.id = password.user_id;   # 左边的全部显示
                    select * from userinfo right join password on userinfo.id = password.user_id;  # 右边的全部显示
                    select * from userinfo inner join password on userinfo.id = password.user_id;  # 将出现null的隐藏
                        mysql> select * from userinfo;
                        +----+----------+----------+
                        | id | username | usertype |
                        +----+----------+----------+
                        |  1 | root1    |        1 |
                        |  2 | root2    |        1 |
                        |  3 | root3    |        2 |
                        |  4 | root4    |        2 |
                        |  5 | root5    |        2 |
                        |  6 | root6    |       33 |
                        |  7 | root7    |        3 |
                        |  8 | root8    |       33 |
                        |  9 | root9    |        3 |
                        +----+----------+----------+
                        9 rows in set (0.00 sec)
                                            
                        mysql> select * from password;
                        +----+---------+----------+
                        | id | user_id | password |
                        +----+---------+----------+
                        |  1 |       6 | asdfasdf |
                        |  2 |       8 | asdfasdf |
                        +----+---------+----------+
                        2 rows in set (0.00 sec)
                        
                        
                        mysql> select * from userinfo,password where userinfo.id = password.user_id;
                        +----+----------+----------+----+---------+----------+
                        | id | username | usertype | id | user_id | password |
                        +----+----------+----------+----+---------+----------+
                        |  6 | root6    |       33 |  1 |       6 | asdfasdf |
                        |  8 | root8    |       33 |  2 |       8 | asdfasdf |
                        +----+----------+----------+----+---------+----------+
                        2 rows in set (0.00 sec)
                                            
                        
                        mysql> select * from userinfo left join password on userinfo.id = password.user_id;
                        +----+----------+----------+------+---------+----------+
                        | id | username | usertype | id   | user_id | password |
                        +----+----------+----------+------+---------+----------+
                        |  6 | root6    |       33 |    1 |       6 | asdfasdf |
                        |  8 | root8    |       33 |    2 |       8 | asdfasdf |
                        |  1 | root1    |        1 | NULL |    NULL | NULL     |
                        |  2 | root2    |        1 | NULL |    NULL | NULL     |
                        |  3 | root3    |        2 | NULL |    NULL | NULL     |
                        |  4 | root4    |        2 | NULL |    NULL | NULL     |
                        |  5 | root5    |        2 | NULL |    NULL | NULL     |
                        |  7 | root7    |        3 | NULL |    NULL | NULL     |
                        |  9 | root9    |        3 | NULL |    NULL | NULL     |
                        +----+----------+----------+------+---------+----------+
                        9 rows in set (0.00 sec)

                        mysql> select * from userinfo right join password on userinfo.id = password.user_id;
                        +------+----------+----------+----+---------+----------+
                        | id   | username | usertype | id | user_id | password |
                        +------+----------+----------+----+---------+----------+
                        |    6 | root6    |       33 |  1 |       6 | asdfasdf |
                        |    8 | root8    |       33 |  2 |       8 | asdfasdf |
                        +------+----------+----------+----+---------+----------+
                        2 rows in set (0.00 sec)
                        
                        
                        
                        
                    select
                        score.sid,course.cname,student.sname,class.caption,teacher.tname
                    from 
                        score
                    left join student on score.student_id = student.sid
                    left join course on score.corse_id = course.cid
                    left join class on student.class_id = class.cid
                    left join teacher on course.teacher_id = teacher.tid;
                    

                    
今日内容:
    navicat
        使用创建表(外键)
        新建查询
        
        转储sql文件
    
    命令行
        备份:数据表结构+数据:
        mysqldump -u root test > d:\test.sql
        备份:数据表结构:
        mysqldump -u root -d test > d:\test.sql
        
        执行文件(导入文件):
        create database db1;
        mysqldump -u root -d db5 < d:\test.sql -p;
                    
                    
    临时表的概念!!!
    select a,b from (select a,b,c from abc) as B:
                    
                    
                    
                    
                    
        case when number < 60 then 0 else 1 end
        if(isnull(score.num),0,score.num)

pymysql模块
    pip3 install pymysql 
    python模块:对数据库进行操作(SQL语句)

    1、python实现用户登录
    2、mysql保存数据
    

    - 连接、关闭(cursor)
    - execute()   --sql注入
    - 增删改:conn.commit()
    - fetchone fetchall
    - 获取插入数据自增ID cursor.lastrowid



练习:
    权限管理
    
        权限表:
            1 订单管理
            2 用户管理
            3 菜单管理
            4 权限分配
            5 bug管理
        
        用户表:
            id username pw
            1  alex     123
            2  egon     123
        
        用户权限关系表
            1 1
            1 2
            2 1
        
    python实现:
        某个用户登陆后,查看自己拥有的权限

        
        
        基于角色的权限管理
            用户信息表
            
            权限表
            
            角色表
            
            角色-权限
            
            用户-角色
        
        ===>
            1、基于角色的权限管理
            2、需求分析
            
        

        
回顾:
    SQL语句:
        数据行:
            临时表:(select * from tb where id > 10) as A
            指定映射:
                select id,name,1,sum(x)/count(1)
            条件:
                case when id>10 then xx else yy end
            三元运算:
                if(isnull(x),0,xx)
            补充:
                左右连表:join
                上下连表:union
                    select sid,sname from student
                    union  # 自动去重
                    select tid,tname from teacher
                    
                    select sid,sname from student
                    union all  # 不去重
                    select sid,sname from student
        

DAY5 内容
    1、视图
        100个SQL语句:
            select ....
            
        某个查询语句设置别名,日后方便使用
        -创建:
            create view 视图平成 as SQL语句
            PS:虚拟的
        -修改
            alter view 视图名称 as  SQL语句
        -删除
            drop view 视图名称;
            
    2、触发器
        对某张表进行增删改查时,可以使用触发器自定义关联行为
        insert into tb(。。。)
        new 代指新数据,插入、更新具有new数据
        old 代指老数据,删除、更新均有old数据
        
        
        delimiter //  # 修改;为//,
        create trigger t1 before insert on student for each ROW
        BEGIN
        insert into teacher(tname) values("abcd"或者new.name);  # new是新插入的数据,选择name字段
        insert 。。。。;
        insert .....;
        END
        //  # 完事
        delimiter ;  # 修改回来
        
    3、函数
        内置函数:
            时间格式化 curdate()  DATE_FORMAT
        自定义函数
            delimiter \\
                create FUNCTION f1(
                    i1 int,
                    i2 int)
                returns int
                BEGIN  # 函数主体
                    declare num int default 0;
                    set num = i1+i2;
                    return(num);
                end \\
            delimiter ;
            
            select f1(11,100);
    
    4、存储过程
        保存在mysql上的一个别名 => 一坨SQL语句
        
        别名()
        用于替代程序员写SQL语句
    
        方式一:
            mysql:存储过程
            程序:调用存储过程
        方式二:
            mysql:不做
            程序:sql语句
        方式三:
            mysql:不做
            程序:类和对象(SQL语句)
            
        1、简单
            delimiter //
                create procedure p1()
                BEGIN
                    select * from student;
                    insert into teacher(tname) values("ct");
                END//
            delimiter ;
            
        2、传参数(in,out,inout)
            delimiter //
                create procedure p2(
                    in n1 int,
                    in n2 int
                )
                BEGIN
                    select * from student where sid > n1;
                    
                END//
                delimiter ;
            call p2(12,2);
            cursor.callproc("p2",(12,2))
            
        3、传参数 out
            delimiter //
                create procedure p3(
                    in n1 int,
                    out n2 int
                )
                BEGIN
                    set n2 = 123123;
                    select * from student where sid > n1;
                    
                END//
                delimiter ;
            
            set @v1 = 0;
            call p2(12,@v1);
            select @v1;
    
    
            cursor.callproc("p3",(15,2))
            r1 = cursor.fetchall()
            print(r1)
            
            cursor.execute("select @_p3_0,@_p3_1")
            r2 = cursor.fetchall()
            print(r2)
    
            ======> 特性
                a.可传参
                b.pymysql
            
                    cursor.callproc("p3",(15,2))
                    r1 = cursor.fetchall()
                    print(r1)
                    
                    cursor.execute("select @_p3_0,@_p3_1")
                    r2 = cursor.fetchall()
                    print(r2)
            
            为什么有结果集又有out伪造的返回值?
            
                delimiter //
                create procedure p3(
                    in n1 int,
                    inout n2 int  用于标识存储过程的执行结果 1,2,3
                )
                begin 
                    insert into vv(..)
                    insert into vv(..)
                    insert into vv(..)
                    insert into vv(..)
                    insert into vv(..)
                end //
                delimiter ;
                
        4、事务
            delimiter //
            creater procedure p4(
                out status int
            )
            begin
                1.声明如果出现异常则执行{
                    set status = 1;
                    rollback;
                }
                
                开始事务
                    -- a账户-100元
                    -- b账户+90元
                    -- c账户+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; 
                 
                  START TRANSACTION; 
                    DELETE from tb1;
                    insert into tb2(name)values('seven');
                  COMMIT; 
                 
                  -- SUCCESS 
                  set p_return_code = 0; 
                 
                  END\\
            delimiter ;    
            
        5、游标
            A
            id  num
            1    9
            2    8


            B
            id  num
            1   9+1
            2   8+2

            1、声明游标
            2、获取A表中的数据
                my_cursor select id,num from A;

            3、for row_id,row_num in my_cursor:
                # 检测循环是否还有数据,如果无数据
                # break;
                insert into B(id,num) values(row_id+row_num)
                
                
                
                
                
            delimiter //
                create procedure p6()
                begin 
                    declare row_id int; -- 自定义变量1  
                    declare row_num int; -- 自定义变量2  
                    declare done INT DEFAULT FALSE;  -- 声明标志位
                    declare tmp int


                    declare my_cursor CURSOR FOR select id,num from A;
                    declare CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;  # 如果cursor找不到值,则done=True
                    
                    open my_cursor;
                        xxoo: LOOP
                            fetch my_cursor into row_id,row_num;
                            if done then        # 如果为True,则退出循环
                                leave xxoo;
                            END IF;
                            set tmp = row_num + row_id
                            insert into B(num) values(tmp);
                        end loop xxoo;
                    close my_cursor;
                end  //
            delimter ;    
            
        6、动态执行sql(放sql注入)
            delimiter //
                create procedure p7(
                    in tpl varchar(255),
                    in arg int
                )
                begin
                    1.预检测某个东西 SQL语句合法性
                    2.格式化sql = tpl + arg
                    3.执行sql语句
                    set @xo = arg;
                    PREPARE prod FROM 'select * from student where sid > ?';
                    EXECUTE prod USING @xo;
                    DEALLOCATE prepare prod; 
                
                end //
            delimiter ;
            
            
            call p7("select * from tb where id > ?",9)
            
            ======>
                delimiter \\
                    CREATE PROCEDURE p7 (
                        in nid int
                    )
                    BEGIN
                        set @nid = nid;
                        PREPARE prod FROM 'select * from student where sid > ?';
                        EXECUTE prod USING @nid;
                        DEALLOCATE prepare prod; 
                    END\\
                delimiter ;
        
        

    
    5、索引
        作用:
            约束
            加速查找
        索引的种类
            - 普通索引:加速查找
            - 主键索引:加速查找 + 不能为空 + 不能重复
            - 唯一索引:加速查找 + 不能重复
            - 联合索引(多列)
                - 联合主键索引
                - 联合唯一索引
                - 联合普通索引
        加速查找
            select * from tb where name="adf"
            select * from tb where id = 999;
            
            create index ix_name on tb_name(name);
            假设:
                id name email
                。。。
                
                无索引:从前到后一次查找
                索引:
                    id 创建额外文件(某种格式存储的)
                    name 创建额外文件(某种格式存储的) 
                    name + email 创建额外文件(某种格式存储的)
                
                
                索引种类(某种格式存储的):
                    hash索引:
                        单值快
                        范围
                    btree索引
                        二叉树
    
            =======> 结果:快 《========
            建立索引:
                - a.额外的文件保存特殊的数据结构
                - b.查询款:插入更新删除慢
                - c.命中索引
                    select * from info where email="...";快
                    select * from info where email like "sadfdf%"; 不命中索引,慢
                主键索引:
                
                
                普通索引:
                    - create index index_name on table_name(列名)
                    - drop index index_name on table_name
                
                唯一索引:
                    - create unique index index_name on table_name(列名)
                    - drop unique index index_name on table_name
                    
                组合索引:
                    - create index index_name on table_name(列名,列名,列名)
                    - drop index index_name on table_name            
                    - create unique index index_name on table_name(列名,列名,列名)
                    - drop unique index index_name on table_name
                    
                    create index index_name on info(name,email);
                    -最左前缀匹配
                        select * from info where name = "a";
                        select * from info where name = "a" and email="a@qq.com";
                        
                        select * from info where email="a@qq.com"; 不走索引
                        
                    组合索引效率 > 索引合并
                        组合索引
                            - (name,email)
                            select * from info where name = "a" and email="a@qq.com"
                            select * from info where name = "a";
                        索引合并:
                            - name
                            - email
                            select * from info where name = "a" and email="a@qq.com"
                            select * from info where name = "a";
                            select * from info where email="a@qq.com"; 
                            
    2、频繁查找的列创建索引
        创建索引
        命中索引                
            
            以下会影响查找速度
            - like 
            - 函数
            - or
                如果 a or b 中,b没做索引,name会影响速度
            - 类型不一致
                即 如果 name 是char类型,但你select .. where name = 999;那么就会影响速度;
                (主键除外)
            
            - !=
                不走索引
                (主键除外)
            - >
                不走索引
                主键或者数字,会走索引
            - order by
                不走索引:
                select name from .. where email = ..;
                            
                走索引:
                select name from .. where name ="a";
                (主键除外)
            
        其他注意事项
            - 避免使用select *- count(1)或count(列) 代替 count(*)   √
            - 创建表时尽量时 char 代替 varchar   √
            - 表的字段顺序固定长度的字段优先
            - 组合索引代替多个单列索引(经常使用多个条件查询时)
            - 尽量使用短索引
            - 使用连接(JOIN)来代替子查询(Sub-Queries)
            - 连表时注意条件类型需一致
            - 索引散列值(重复少)不适合建索引,例:性别不适合   √
        
    3、时间
        执行计划:让mysql预估执行操作
            explain select * from tb  # 不会真实执行,会预估时间
            慢:
                select * from userinfo3 where name="alex"
                explain select * from userinfo3 where name="alex"
                type:ALL(全表扫描)
                    select * from userinfo3 limit 1;
            快:
                select * from userinfo3 where emai="alex"
                type:const(走索引)
    
    4、DBA工作
        慢日志
            - 执行时间 > 10
            - 未命中索引
            - 日志文件路径
        
        配置:
            - 内存
                show variables like "%query%"
                set global 变量名 =- 配置文件
                mysqld -- defaults-file="D:\....\my-default.ini"
                
                my.conf内容
                    set global slow_query_log=ON
                    slow_querey_log_file=D:/...
                注意:修改之前备份,修改配置文件之后,需要重启服务
                    
    5、***分页***
        a.select * from info limit 0,10
        b.
            - 不让看
            - 索引表中扫:
                select * from info where id in (
                    select id from info limit 200000,10
                )
            - 方案:
                记录当前页最大或最小ID
                1.页面只有上一页,下一页
                    max_id
                    min_id
                    下一页:
                        select * from info where id > max_id limit 10;
                    上一页:
                        select * from info where id < min_id order by id desc limit 10;
                2.上一页,192,193,194,195,[196],197,198,199,下一页
                    
                    select * from info where id in (
                        select id from (select id from info where id > max_id limit 30) as N  order N.id desc limit 10
                    )
                    
                    
                    
        c.
            id不连续,无法使用id范围进行查找
            
            

            
            
            
            
            
            
            
            
            
            
            
            
            
            
    
    
    
    6、ORM操作
        - 类对象对数据进行操作
        
        1、ORM框架:SQLAlchemy
            - 作用:
                1.提供简单的规则
                2.自动转换为sql
            
            - DB first:手动创建数据库以及表 -> ORM框架 -> 自动生成类
            - code first:手动创建类和数据库  -> ORM框架  -> 以及表
        
            a.功能
                - 创建数据库表
                    - 连接数据库(非SQLAlchemy,pymysql,mysqldb,。。。)
                    - 类转换SQL语句
                    
                    
                - 操作数据行
                    增
                    删
                    改
                    查
                
                - 便利的功能
                
            
            
            subquery
            as_scalar()
                
        
            问题1.获取用户信息以及与其关联的用户类型名称
                relationship
            问题2.获取用户类型
                backref
        
        
        
        
        
        2、自己开发web框架
            - socket
            - http协议
            - HTML知识
            - 数据库(pymysql,SQLAlchemy)
        

        
        
        
        
        
        
        
        
        
内容回顾:
    1、无面向对象,完全可以编程
    
        def exc1(host,port,db,charset,SQL):
            # 连接
            execute("insert")
            return arg
        
        def exc2(host,port,db,charset,proc_name):
            callproc(xxx)
            return xxx
        
        
        class Person:
                def __init__(self,name):
                    self.name = name
                
                def speak(self):
                    pass

        
    面向对象
    
        1、提取共性
        2、分类
        3、模板“约束”
            - 一类事务共同具有:属性和行为
            class Person:
                def __init__(self,name):
                    self.name = name
                
                def speak(self):
                    pass
        4、当一类函数公用同样参数时,可以转变成类进行 - 分类
        
        
        
        
        
        
        
        
        
        
        
        
        
        
笔记

 

练习题

1、自行创建测试数据


2、查询“生物”课程比“物理”课程成绩高的所有学生的学号;
    select 
    S3.sid,
    S3.sname,
    shengwu,
    wuli
    from 
    (select 
    student.sid,
    student.sname,
    (select number from score as S1 where S1.corse_id=(select cid from course where course.cname="生物") and S2.student_id=S1.student_id) as shengwu,
    (select number from score as S1 where S1.corse_id=(select cid from course where course.cname="物理") and S2.student_id=S1.student_id) as wuli
    from 
    score as S2
    left join course on course.cid=S2.corse_id
    left join student on S2.student_id=student.sid
    group by S2.student_id) as S3
    where S3.shengwu > S3.wuli
    +------+---------+---------+------+
    | sid  | sname   | shengwu | wuli |
    +------+---------+---------+------+
    |    8 |  范富强 |       7 |    1 |
    |   17 | 何荣斌  |      90 |   10 |
    |   18 | 梁永峰  |      62 |   41 |
    |   19 | 何梧彬  |      72 |   28 |
    +------+---------+---------+------+


3、查询平均成绩大于60分的同学的学号和平均成绩;
    select * from student left join score on student.sid=score.student_id;
    select student.sid,avg(score.number) from student left join score on student.sid=score.student_id group by student.sid;
    select student.sid,avg(score.number) from student left join score on student.sid=score.student_id group by student.sid having avg(score.number)>60;
    +-----+-------------------+
    | sid | avg(score.number) |
    +-----+-------------------+
    |  13 |           63.6667 |
    |  14 |           62.2222 |
    |  15 |           68.2222 |
    |  16 |           61.3333 |
    |  17 |           61.8889 |
    +-----+-------------------+
    5 rows in set (0.00 sec)


4、查询所有同学的学号、姓名、选课数、总成绩;
    select * from student left join score on student.sid=score.student_id;
    select student.sid,student.sname,count(score.corse_id),sum(score.number) from student left join score on student.sid=score.student_id group by student.sid;
    +-----+---------+-----------------------+-------------------+
    | sid | sname   | count(score.corse_id) | sum(score.number) |
    +-----+---------+-----------------------+-------------------+
    |   1 | 郭绍峰  |                     9 |               414 |
    |   2 | 李少鑫  |                     9 |               352 |
    |   3 | 曹名学  |                     9 |               399 |
    |   4 | 熊总    |                     9 |               470 |
    |   5 | 李贯洪  |                     9 |               522 |
    |   6 | 杨为硕  |                     9 |               490 |
    |   7 | 陈慧冰  |                     9 |               460 |
    |   8 |  范富强 |                     9 |               264 |
    |   9 | 胡云耀  |                     9 |               492 |
    |  10 | 刘晓东  |                     9 |               384 |
    |  11 | 程嘉城  |                     9 |               410 |
    |  12 | 黄伟炫  |                     9 |               356 |
    |  13 | 童睿    |                     9 |               573 |
    |  14 | 何勇泳  |                     9 |               560 |
    |  15 | 樊明    |                     9 |               614 |
    |  16 | 立胜    |                     9 |               552 |
    |  17 | 何荣斌  |                     9 |               557 |
    |  18 | 梁永峰  |                     9 |               404 |
    |  19 | 何梧彬  |                     9 |               527 |
    +-----+---------+-----------------------+-------------------+
    

5、查询姓“李”的老师的个数;
    select count(tid) from teacher where tname like "叶%";
    select count(tid) from teacher where tname like "李%";

6、查询没学过“叶平”老师课的同学的学号、姓名;
    select * from 
    student
    where 
    student.sid not in 
    (select score.student_id from score
    left join course on course.cid=score.corse_id
    left join teacher on teacher.tid=course.teacher_id
    where teacher.tname="高松")
    +-----+--------+--------+----------+
    | sid | sname  | gender | class_id |
    +-----+--------+--------+----------+
    |   4 | 熊总   | 女     |        4 |
    |   5 | 李贯洪 | 女     |        4 |
    |   6 | 杨为硕 | 男     |        6 |
    |   7 | 陈慧冰 | 女     |        5 |
    |  12 | 黄伟炫 | 男     |        2 |
    |  20 | 范富强 | 男     |        2 |
    |  21 | 曹名学 | 男     |        2 |
    +-----+--------+--------+----------+

7、查询学过“001”并且也学过编号“002”课程的同学的学号、姓名;
    select
     * 
    from 
    student 
    where 
    student.sid in (select score.student_id from score where score.corse_id=1) 
    and 
    student.sid in (select score.student_id from score where score.corse_id=2) 
    +-----+---------+--------+----------+
    | sid | sname   | gender | class_id |
    +-----+---------+--------+----------+
    |   3 | 曹名学  | 男     |        1 |
    |   8 |  范富强 | 女     |        3 |
    |   9 | 胡云耀  | 男     |        4 |
    |  10 | 刘晓东  | 女     |        1 |
    |  13 | 童睿    | 女     |        6 |
    |  14 | 何勇泳  | 女     |        5 |
    |  15 | 樊明    | 男     |        5 |
    |  16 | 立胜    | 女     |        3 |
    |  18 | 梁永峰  | 男     |        1 |
    +-----+---------+--------+----------+

8、查询学过“叶平”老师所教的所有课的同学的学号、姓名;
    select score.student_id,student.sname,count(score.student_id) from 
    (select course.cid from course
    left join teacher on teacher.tid=course.teacher_id
    where teacher.tname="高松") as A
    left join score on A.cid=score.corse_id
    left join student on student.sid=score.student_id
    group by score.student_id having count(score.student_id)=2
    +------------+---------+-------------------------+
    | student_id | sname   | count(score.student_id) |
    +------------+---------+-------------------------+
    |          3 | 曹名学  |                       2 |
    |          8 |  范富强 |                       2 |
    |          9 | 胡云耀  |                       2 |
    |         10 | 刘晓东  |                       2 |
    |         13 | 童睿    |                       2 |
    |         14 | 何勇泳  |                       2 |
    |         15 | 樊明    |                       2 |
    |         16 | 立胜    |                       2 |
    |         18 | 梁永峰  |                       2 |
    +------------+---------+-------------------------+



9、查询课程编号“002”的成绩比课程编号“001”课程低的所有同学的学号、姓名;
    select
    s1.student_id,
    student.sname,
    (select number from score as s2 where corse_id=1 and s2.student_id=s1.student_id) as num1,
    (select number from score as s3 where corse_id=2 and s3.student_id=s1.student_id) as num2
    from
    score as s1
    left join student on student.sid=s1.student_id
    group by s1.student_id having num2>num1
    +------------+---------+------+------+
    | student_id | sname   | num1 | num2 |
    +------------+---------+------+------+
    |          3 | 曹名学  |    9 |   83 |
    |          8 |  范富强 |    7 |   48 |
    |          9 | 胡云耀  |   44 |   91 |
    |         10 | 刘晓东  |   59 |   60 |
    |         13 | 童睿    |   54 |   68 |
    |         14 | 何勇泳  |   38 |   57 |
    |         15 | 樊明    |   53 |   70 |
    |         16 | 立胜    |   73 |   86 |
    |         18 | 梁永峰  |   62 |   98 |
    +------------+---------+------+------+



10、查询有课程成绩小于60分的同学的学号、姓名;
    select student.sid,student.sname from student left join score on score.number<60 and score.student_id=student.sid group by student.sid;

11、查询没有学全所有课的同学的学号、姓名;
    select student.sid,student.sname,count(score.number)
    from student
    left join score on student.sid=score.student_id
    group by student.sid having count(score.number)<(select count(1) from course);
    +-----+---------+---------------------+
    | sid | sname   | count(score.number) |
    +-----+---------+---------------------+
    |   1 | 郭绍峰  |                   4 |
    |   2 | 李少鑫  |                   4 |
    |   3 | 曹名学  |                   7 |
    |   4 | 熊总    |                   6 |
    |   5 | 李贯洪  |                   8 |
    |   6 | 杨为硕  |                   8 |
    |   7 | 陈慧冰  |                   7 |
    |   8 |  范富强 |                   8 |
    |   9 | 胡云耀  |                   6 |
    |  10 | 刘晓东  |                   6 |
    |  11 | 程嘉城  |                   5 |
    |  12 | 黄伟炫  |                   5 |
    |  13 | 童睿    |                   8 |
    |  14 | 何勇泳  |                   7 |
    |  15 | 樊明    |                   8 |
    |  17 | 何荣斌  |                   8 |
    |  18 | 梁永峰  |                   8 |
    |  19 | 何梧彬  |                   6 |
    |  20 | 范富强  |                   0 |
    |  21 | 曹名学  |                   0 |
    +-----+---------+---------------------+

12、查询至少有一门课与学号为“001”的同学所学相同的同学的学号和姓名;
    select score.student_id,student.sname from 
    (select score.corse_id from score where score.student_id=1) as A
    left join score on score.corse_id=A.corse_id
    left join student on student.sid=score.student_id
    where score.student_id!=1
    group by student_id
    +------------+---------+
    | student_id | sname   |
    +------------+---------+
    |          2 | 李少鑫  |
    |          3 | 曹名学  |
    |          4 | 熊总    |
    |          5 | 李贯洪  |
    |          6 | 杨为硕  |
    |          7 | 陈慧冰  |
    |          8 |  范富强 |
    |          9 | 胡云耀  |
    |         10 | 刘晓东  |
    |         11 | 程嘉城  |
    |         12 | 黄伟炫  |
    |         13 | 童睿    |
    |         14 | 何勇泳  |
    |         15 | 樊明    |
    |         16 | 立胜    |
    |         17 | 何荣斌  |
    |         18 | 梁永峰  |
    |         19 | 何梧彬  |
    +------------+---------+

13、查询至少学过学号为“001”同学所选课程中任意一门课的其他同学学号和姓名;
    select score.student_id,student.sname,count(1)
    from score 
    left join student on student.sid=score.student_id
    where score.corse_id in (select score.corse_id from score where score.student_id=1) and score.student_id != 1
    group by score.student_id having count(1)=((select count(score.corse_id) from score where score.student_id=1))
    +------------+--------+----------+
    | student_id | sname  | count(1) |
    +------------+--------+----------+
    |          2 | 李少鑫 |        4 |
    |         11 | 程嘉城 |        4 |
    |         15 | 樊明   |        4 |
    |         16 | 立胜   |        4 |
    |         17 | 何荣斌 |        4 |
    |         18 | 梁永峰 |        4 |
    +------------+--------+----------+


14、查询和“002”号的同学学习的课程完全相同的其他同学学号和姓名;
    select A.student_id,A.sname,A.cou
    from
    (
    select score.student_id,student.sname,count(1) as cou
    from score
    left join student on student.sid=score.student_id
    where score.corse_id in (select score.corse_id from score where score.student_id=1) and score.student_id != 1
    group by score.student_id having count(1)=((select count(score.corse_id) from score where score.student_id=1))
    ) as A where A.cou=(select count(1) as cou from score where score.student_id=A.student_id)
    +------------+--------+-----+
    | student_id | sname  | cou |
    +------------+--------+-----+
    |          2 | 李少鑫 |   4 |
    +------------+--------+-----+

    
15、删除学习“叶平”老师课的SC表记录;
    delete from score where score.corse_id in 
    (
    select course.cid from course
    left join teacher on course.teacher_id=teacher.tid
    where teacher.tname="夏平湖")

    受影响的行: 27
    时间: 0.000ms


16、向SC表中插入一些记录,这些记录要求符合以下条件:①没有上过编号“002”课程的同学学号;②插入“002”号课程的平均成绩; 

    insert into score(student_id,corse_id,number) select student.sid,
    2,
    (select avg(number) from score where score.corse_id=2)
    from student 
    where student.sid not in 
    (select score.student_id from score where score.corse_id=2);


17、按平均成绩从低到高显示所有学生的“语文”、“数学”、“英语”三门的课程成绩,按如下形式显示: 学生ID,语文,数学,英语,有效课程数,有效平均分;
    select 
    A.student_id,
    (select number from score where score.corse_id=(select course.cid from course where course.cname="语文") and student_id=A.student_id)as yuwen,
    (select number from score where score.corse_id=(select course.cid from course where course.cname="数学") and student_id=A.student_id)as shuxue,
    (select number from score where score.corse_id=(select course.cid from course where course.cname="英语") and student_id=A.student_id)as yingyu,
    count(1),
    avg(number)
    from score as A
    group by A.student_id
    order by avg(number)
    +------------+-------+--------+--------+----------+-------------+
    | student_id | yuwen | shuxue | yingyu | count(1) | avg(number) |
    +------------+-------+--------+--------+----------+-------------+
    |          8 |  NULL |     41 |     28 |        5 |     25.6000 |
    |         12 |    45 |   NULL |     15 |        4 |     33.7500 |
    |          3 |  NULL |     23 |     14 |        5 |     40.4000 |
    |          7 |    11 |     77 |     50 |        5 |     43.2000 |
    |         18 |    59 |     57 |      1 |        7 |     46.2857 |
    |          4 |     3 |     90 |      1 |        5 |     49.6000 |
    |          2 |    47 |     74 |   NULL |        5 |     52.8000 |
    |         19 |    35 |     94 |     28 |        6 |     54.3333 |
    |          1 |    20 |    100 |   NULL |        5 |     55.0000 |
    |         11 |    38 |     60 |     92 |        6 |     55.1667 |
    |         17 |    88 |     32 |     93 |        7 |     59.0000 |
    |         10 |  NULL |   NULL |     59 |        4 |     59.2500 |
    |         16 |    24 |     31 |     17 |        7 |     59.4286 |
    |          6 |    26 |     18 |     90 |        6 |     60.0000 |
    |         13 |    71 |   NULL |     45 |        6 |     60.1667 |
    |         14 |    47 |   NULL |     88 |        6 |     65.0000 |
    |         21 |  NULL |   NULL |   NULL |        1 |     69.0000 |
    |         20 |  NULL |   NULL |   NULL |        1 |     69.0000 |
    |          5 |    51 |     78 |     65 |        6 |     71.6667 |
    |         15 |    71 |     72 |     84 |        7 |     71.7143 |
    |          9 |  NULL |     33 |     99 |        3 |     74.3333 |
    +------------+-------+--------+--------+----------+-------------+



18、查询各科成绩最高和最低的分:以如下形式显示:课程ID,最高分,最低分;
    select corse_id,max(number),min(number) from score group by corse_id;
    +----------+-------------+-------------+
    | corse_id | max(number) | min(number) |
    +----------+-------------+-------------+
    |        1 |          90 |           7 |
    |        2 |          98 |          20 |
    |        3 |         100 |           1 |
    |        4 |          88 |           1 |
    |        5 |          94 |           6 |
    |        6 |          99 |           1 |
    |        7 |          99 |           2 |
    |        8 |          98 |           3 |
    |        9 |          93 |           2 |
    +----------+-------------+-------------+

19、按各科平均成绩从低到高和及格率的百分数从高到低顺序;
    select 
    corse_id,
    avg(number),
    sum(case when number < 60 then 0 else 1 end),sum(1),
    sum(case when number < 60 then 0 else 1 end)/sum(1) as jgl
    from score
    group by corse_id
    order by avg(number) asc,jgl desc


20、课程平均分从高到低显示(现实任课老师);
    select corse_id,avg(number),teacher.tname from score
    left join course on score.corse_id=course.cid
    left join teacher on course.teacher_id=teacher.tid
    group by corse_id
    order by avg(number) desc

21、查询各科成绩前三名的记录:(不考虑成绩并列情况) 
    select * from 
    (
    select 
    student_id,
    corse_id,
    number,
    (select number from score as s2 where s2.corse_id=s1.corse_id order by number desc limit 0,1) as 1st,
    (select number from score as s2 where s2.corse_id=s1.corse_id order by number desc limit 1,1) as 2nd,
    (select number from score as s2 where s2.corse_id=s1.corse_id order by number desc limit 2,1) as 3rd
    from score as s1
    ) as B
    where B.number >= B.3rd


22、查询每门课程被选修的学生数;
    select corse_id,count(1) from score group by corse_id having count(1)>12


23、查询出只选修了一门课程的全部学生的学号和姓名;
    select student_id,count(1) from score group by student_id having count(1) =4


24、查询男生、女生的人数;
    select gender,count(sid) from student group by gender;
    +--------+------------+
    | gender | count(sid) |
    +--------+------------+
    | 男     |          6 |
    | 女     |         13 |
    +--------+------------+
    2 rows in set (0.00 sec)
    
25、查询姓“张”的学生名单;
    select * from student where student.sname like "黄%";
    +-----+--------+--------+----------+
    | sid | sname  | gender | class_id |
    +-----+--------+--------+----------+
    |  12 | 黄伟炫 | 男     |        2 |
    +-----+--------+--------+----------+
    1 row in set (0.00 sec)

26、查询同名同姓学生名单,并统计同名人数;
    select sname,count(1) from student group by sname  having count(1) > 1



27、查询每门课程的平均成绩,结果按平均成绩升序排列,平均成绩相同时,按课程号降序排列;
    select * from score left join course on score.corse_id=course.cid;
    select course.cid,course.cname,avg(score.number) from score right join course on score.corse_id=course.cid group by course.cid;
    select course.cid,course.cname,avg(score.number) from score right join course on score.corse_id=course.cid group by course.cid order by avg(score.number) asc;
    select course.cid,course.cname,avg(score.number) from score right join course on score.corse_id=course.cid group by course.cid order by avg(score.number) asc,course.cid asc;
    +-----+-------+-------------------+
    | cid | cname | avg(score.number) |
    +-----+-------+-------------------+
    |   4 | 语文  |           36.4737 |
    |   1 | 生物  |           46.5789 |
    |   6 | 英语  |           49.2105 |
    |   5 | 数学  |           50.4737 |
    |   7 | 化学  |           54.1053 |
    |   9 | 地理  |           54.2632 |
    |   3 | 物理  |           56.2632 |
    |   8 | 政治  |           56.4737 |
    |   2 | 体育  |           59.3158 |
    +-----+-------+-------------------+


28、查询平均成绩大于85的所有学生的学号、姓名和平均成绩;
    select 
    score.student_id,
    student.sname,
    avg(number)
    from score
    left join student on student.sid=score.student_id
    group by score.student_id having avg(number) > 70
    +------------+--------+-------------+
    | student_id | sname  | avg(number) |
    +------------+--------+-------------+
    |          5 | 李贯洪 |     71.6667 |
    |          9 | 胡云耀 |     74.3333 |
    |         15 | 樊明   |     71.7143 |
    +------------+--------+-------------+



29、查询课程名称为“数学”,且分数低于60的学生姓名和分数;
    select score.student_id,student.sname,score.number from score 
    left join course on score.corse_id=course.cid
    left join student on score.student_id=student.sid
    where score.number<60 and course.cname="生物"
    +------------+--------+--------+
    | student_id | sname  | number |
    +------------+--------+--------+
    |          1 | 郭绍峰 |      8 |
    |          2 | 李少鑫 |     59 |
    |          3 | 曹名学 |      9 |
    |         10 | 刘晓东 |     59 |
    |         11 | 程嘉城 |     46 |
    |         13 | 童睿   |     54 |
    |         14 | 何勇泳 |     38 |
    |         15 | 樊明   |     53 |
    +------------+--------+--------+


30、查询课程编号为003且课程成绩在80分以上的学生的学号和姓名; 
    select student.sid,student.sname from score 
    left join student on student.sid=score.student_id
    where corse_id=3 and number > 80
    +------+--------+
    | sid  | sname  |
    +------+--------+
    |    5 | 李贯洪 |
    |    6 | 杨为硕 |
    |   14 | 何勇泳 |
    |   15 | 樊明   |
    |   16 | 立胜   |
    +------+--------+


31、求选了课程的学生人数
    select count(A.student_id)
    from 
    (select student_id from score group by student_id) as A

    /
    
    select count(DISTINCT student_id) from score;



32、查询选修“杨艳”老师所授课程的学生中,成绩最高的学生姓名及其成绩;
    select A.corse_id,A.number,student.sname from student
    inner join
    (select score.corse_id,score.number,score.student_id from score 
    left join course on course.cid=score.corse_id
    left join teacher on teacher.tid=course.teacher_id
    where teacher.tname like "高%") as A
    on A.student_id=student.sid
    order by A.number desc
    limit 0,1




33、查询各个课程及相应的选修人数;
    select course.cid,course.cname,count(student.sid) from course
    left join score on course.cid=score.corse_id
    left join student on score.student_id=student.sid
    group by course.cid;
    +-----+-------+--------------------+
    | cid | cname | count(student.sid) |
    +-----+-------+--------------------+
    |   1 | 生物  |                 19 |
    |   2 | 体育  |                 19 |
    |   3 | 物理  |                 19 |
    |   4 | 语文  |                 19 |
    |   5 | 数学  |                 19 |
    |   6 | 英语  |                 19 |
    |   7 | 化学  |                 19 |
    |   8 | 政治  |                 19 |
    |   9 | 地理  |                 19 |
    +-----+-------+--------------------+

34、查询不同课程但成绩相同的学生的学号、课程号、学生成绩;
    select A.student_id,A.corse_id,A.number
    from 
    score as A,score as B
    where A.number=B.number and A.corse_id!=B.corse_id


35、查询每门课程成绩最好的前两名;
 
    select 
    A.corse_id,
    (select B.number from score as B where B.corse_id = A.corse_id order by B.number desc limit 0,1) as 1st,
    (select B.number from score as B where B.corse_id = A.corse_id order by B.number desc limit 1,1) as 2nd
    from score as A
    group by A.corse_id
    +----------+------+------+
    | corse_id | 1st  | 2nd  |
    +----------+------+------+
    |        1 |   90 |   73 |
    |        2 |   98 |   91 |
    |        3 |  100 |   95 |
    |        4 |   88 |   71 |
    |        5 |  100 |   94 |
    |        6 |   99 |   93 |
    |        7 |   99 |   96 |
    +----------+------+------+

36、检索至少选修两门课程的学生学号;
    select student_id from score group by student_id having count(1) > 6
    +------------+
    | student_id |
    +------------+
    |         15 |
    |         16 |
    |         17 |
    |         18 |
    +------------+

37、查询全部学生都选修的课程的课程号和课程名;
    select corse_id,count(1) from score group by corse_id having count(1)=(select count(1) from student)
    +----------+----------+
    | corse_id | count(1) |
    +----------+----------+
    |        2 |       21 |
    +----------+----------+


38、查询没学过“叶平”老师讲授的任一门课程的学生姓名;

    select * from student where sid not in (
    select score.student_id from score where corse_id in (select course.cid from course 
    left join teacher on teacher.tid=course.teacher_id
    where teacher.tname="高松")
    group by score.student_id)
    +-----+--------+--------+----------+
    | sid | sname  | gender | class_id |
    +-----+--------+--------+----------+
    |   1 | 郭绍峰 | 女     |        6 |
    |   2 | 李少鑫 | 女     |        1 |
    +-----+--------+--------+----------+


39、查询两门以上不及格课程的同学的学号及其平均成绩;
    select student_id,avg(number) from score where student_id in 
    (
    select student_id from score 
    where number < 60
    group by student_id having count(1)>1)
    group by student_id;
    +------------+-------------+
    | student_id | avg(number) |
    +------------+-------------+
    |          2 |     45.3333 |
    |          3 |     40.4000 |
    |          4 |     49.6000 |
    |          5 |     71.6667 |
    |          6 |     60.0000 |
    |          7 |     43.2000 |
    |          8 |     25.6000 |
    |         10 |     59.2500 |
    |         11 |     55.1667 |
    |         12 |     33.7500 |
    |         13 |     60.1667 |
    |         14 |     65.0000 |
    |         15 |     71.7143 |
    |         16 |     59.4286 |
    |         17 |     59.0000 |
    |         18 |     46.2857 |
    |         19 |     54.3333 |
    +------------+-------------+


40、检索“004”课程分数小于60,按分数降序排列的同学学号;
    select student_id,number from score where corse_id=4 and number<60 order by number desc
    +------------+--------+
    | student_id | number |
    +------------+--------+
    |         18 |     59 |
    |          5 |     51 |
    |          2 |     47 |
    |         14 |     47 |
    |         12 |     45 |
    |         11 |     38 |
    |         19 |     35 |
    |          6 |     26 |
    |         16 |     24 |
    |          1 |     20 |
    |          7 |     11 |
    |          4 |      3 |
    +------------+--------+


41、删除“002”同学的“001”课程的成绩;
    delete from score where student_id=2 and corse_id=4;
    delete from score where student_id=2 and corse_id=4;
    受影响的行: 1
    时间: 0.000ms
练习题 + 答案

 

posted @ 2018-05-07 18:40  fat39  阅读(242)  评论(0编辑  收藏  举报