SQL详解

我们通常可以将SQL分为三类:DDL(数据定义语言)、DML(数据操作语言)和DCL(数据控制语言)。DDL主要用于创建(create)、删除(drop)、修改(alter)数据库中的对象,比如创建、删除和修改二维表;DML主要负责插入数据(insert)、删除数据(delete)、更新数据(update)和查询(select);DCL通常用于授予权限(grant)和召回权限(revoke)。

说明:SQL是不区分大小写的语言,为了书写和识别方便,下面的SQL都使用了小写字母来书写。

DDL(数据定义语言)

  1. -- 如果存在名为school的数据库就删除它
  2. drop database if exists `school`;
  3. -- 创建名为school的数据库并设置默认的字符集和排序方式
  4. create database `school` default character set utf8mb4;
  5. -- 切换到school数据库上下文环境
  6. use `school`;
  7. -- 创建学院表
  8. create table `tb_college`
  9. (
  10. `col_id` int unsigned auto_increment comment '编号',
  11. `col_name` varchar(50) not null comment '名称',
  12. `col_intro` varchar(5000) default '' comment '介绍',
  13. primary key (`col_id`)
  14. ) engine=innodb comment '学院表';
  15. -- 创建学生表
  16. create table `tb_student`
  17. (
  18. `stu_id` int unsigned not null comment '学号',
  19. `stu_name` varchar(20) not null comment '姓名',
  20. `stu_sex` boolean default 1 comment '性别',
  21. `stu_birth` date not null comment '出生日期',
  22. `stu_addr` varchar(255) default '' comment '籍贯',
  23. `col_id` int unsigned not null comment '所属学院',
  24. primary key (`stu_id`),
  25. foreign key (`col_id`) references `tb_college` (`col_id`)
  26. ) engine=innodb comment '学生表';
  27. -- 创建教师表
  28. create table `tb_teacher`
  29. (
  30. `tea_id` int unsigned not null comment '工号',
  31. `tea_name` varchar(20) not null comment '姓名',
  32. `tea_title` varchar(10) default '助教' comment '职称',
  33. `col_id` int unsigned not null comment '所属学院',
  34. primary key (`tea_id`),
  35. foreign key (`col_id`) references `tb_college` (`col_id`)
  36. ) engine=innodb comment '老师表';
  37. -- 创建课程表
  38. create table `tb_course`
  39. (
  40. `cou_id` int unsigned not null comment '编号',
  41. `cou_name` varchar(50) not null comment '名称',
  42. `cou_credit` int unsigned not null comment '学分',
  43. `tea_id` int unsigned not null comment '授课老师',
  44. primary key (`cou_id`),
  45. foreign key (`tea_id`) references `tb_teacher` (`tea_id`)
  46. ) engine=innodb comment '课程表';
  47. -- 创建选课记录表
  48. create table `tb_record`
  49. (
  50. `rec_id` bigint unsigned auto_increment comment '选课记录号',
  51. `sid` int unsigned not null comment '学号',
  52. `cid` int unsigned not null comment '课程编号',
  53. `sel_date` date not null comment '选课日期',
  54. `score` decimal(4,1) comment '考试成绩',
  55. primary key (`rec_id`),
  56. foreign key (`sid`) references `tb_student` (`stu_id`),
  57. foreign key (`cid`) references `tb_course` (`cou_id`),
  58. unique (`sid`, `cid`)
  59. ) engine=innodb comment '选课记录表';

上面的DDL有几个地方需要强调一下:

  • 创建数据库时,我们通过default charset utf8指定了数据库默认使用的字符集,我们推荐使用该字符集,因为utf8能够支持国际化编码。如果将来数据库中用到的字符可能包括类似于Emoji这样的图片字符,也可以将默认字符集设定为utf8mb4(最大4字节的utf-8编码)。查看MySQL支持的字符集可以执行下面的语句。

    1. show character set;
    1. +----------+---------------------------------+---------------------+--------+
    2. | Charset | Description | Default collation | Maxlen |
    3. +----------+---------------------------------+---------------------+--------+
    4. | big5 | Big5 Traditional Chinese | big5_chinese_ci | 2 |
    5. | dec8 | DEC West European | dec8_swedish_ci | 1 |
    6. | cp850 | DOS West European | cp850_general_ci | 1 |
    7. | hp8 | HP West European | hp8_english_ci | 1 |
    8. | koi8r | KOI8-R Relcom Russian | koi8r_general_ci | 1 |
    9. | latin1 | cp1252 West European | latin1_swedish_ci | 1 |
    10. | latin2 | ISO 8859-2 Central European | latin2_general_ci | 1 |
    11. | swe7 | 7bit Swedish | swe7_swedish_ci | 1 |
    12. | ascii | US ASCII | ascii_general_ci | 1 |
    13. | ujis | EUC-JP Japanese | ujis_japanese_ci | 3 |
    14. | sjis | Shift-JIS Japanese | sjis_japanese_ci | 2 |
    15. | hebrew | ISO 8859-8 Hebrew | hebrew_general_ci | 1 |
    16. | tis620 | TIS620 Thai | tis620_thai_ci | 1 |
    17. | euckr | EUC-KR Korean | euckr_korean_ci | 2 |
    18. | koi8u | KOI8-U Ukrainian | koi8u_general_ci | 1 |
    19. | gb2312 | GB2312 Simplified Chinese | gb2312_chinese_ci | 2 |
    20. | greek | ISO 8859-7 Greek | greek_general_ci | 1 |
    21. | cp1250 | Windows Central European | cp1250_general_ci | 1 |
    22. | gbk | GBK Simplified Chinese | gbk_chinese_ci | 2 |
    23. | latin5 | ISO 8859-9 Turkish | latin5_turkish_ci | 1 |
    24. | armscii8 | ARMSCII-8 Armenian | armscii8_general_ci | 1 |
    25. | utf8 | UTF-8 Unicode | utf8_general_ci | 3 |
    26. | ucs2 | UCS-2 Unicode | ucs2_general_ci | 2 |
    27. | cp866 | DOS Russian | cp866_general_ci | 1 |
    28. | keybcs2 | DOS Kamenicky Czech-Slovak | keybcs2_general_ci | 1 |
    29. | macce | Mac Central European | macce_general_ci | 1 |
    30. | macroman | Mac West European | macroman_general_ci | 1 |
    31. | cp852 | DOS Central European | cp852_general_ci | 1 |
    32. | latin7 | ISO 8859-13 Baltic | latin7_general_ci | 1 |
    33. | utf8mb4 | UTF-8 Unicode | utf8mb4_general_ci | 4 |
    34. | cp1251 | Windows Cyrillic | cp1251_general_ci | 1 |
    35. | utf16 | UTF-16 Unicode | utf16_general_ci | 4 |
    36. | utf16le | UTF-16LE Unicode | utf16le_general_ci | 4 |
    37. | cp1256 | Windows Arabic | cp1256_general_ci | 1 |
    38. | cp1257 | Windows Baltic | cp1257_general_ci | 1 |
    39. | utf32 | UTF-32 Unicode | utf32_general_ci | 4 |
    40. | binary | Binary pseudo charset | binary | 1 |
    41. | geostd8 | GEOSTD8 Georgian | geostd8_general_ci | 1 |
    42. | cp932 | SJIS for Windows Japanese | cp932_japanese_ci | 2 |
    43. | eucjpms | UJIS for Windows Japanese | eucjpms_japanese_ci | 3 |
    44. | gb18030 | China National Standard GB18030 | gb18030_chinese_ci | 4 |
    45. +----------+---------------------------------+---------------------+--------+
    46. 41 rows in set (0.00 sec)

    如果要设置MySQL服务启动时默认使用的字符集,可以修改MySQL的配置并添加以下内容

    1. [mysqld]
    2. character-set-server=utf8
  • 在创建表的时候,我们可以在右圆括号的后面通过engine=XXX来指定表的存储引擎,MySQL支持多种存储引擎,可以通过show engines命令进行查看。MySQL 5.5以后的版本默认使用的存储引擎是InnoDB,它正好也就是我们推荐大家使用的存储引擎(因为InnoDB更适合互联网应用对高并发、性能以及事务支持等方面的需求)。

    1. show engines\G
    1. *************************** 1. row ***************************
    2. Engine: InnoDB
    3. Support: DEFAULT
    4. Comment: Supports transactions, row-level locking, and foreign keys
    5. Transactions: YES
    6. XA: YES
    7. Savepoints: YES
    8. *************************** 2. row ***************************
    9. Engine: MRG_MYISAM
    10. Support: YES
    11. Comment: Collection of identical MyISAM tables
    12. Transactions: NO
    13. XA: NO
    14. Savepoints: NO
    15. *************************** 3. row ***************************
    16. Engine: MEMORY
    17. Support: YES
    18. Comment: Hash based, stored in memory, useful for temporary tables
    19. Transactions: NO
    20. XA: NO
    21. Savepoints: NO
    22. *************************** 4. row ***************************
    23. Engine: BLACKHOLE
    24. Support: YES
    25. Comment: /dev/null storage engine (anything you write to it disappears)
    26. Transactions: NO
    27. XA: NO
    28. Savepoints: NO
    29. *************************** 5. row ***************************
    30. Engine: MyISAM
    31. Support: YES
    32. Comment: MyISAM storage engine
    33. Transactions: NO
    34. XA: NO
    35. Savepoints: NO
    36. *************************** 6. row ***************************
    37. Engine: CSV
    38. Support: YES
    39. Comment: CSV storage engine
    40. Transactions: NO
    41. XA: NO
    42. Savepoints: NO
    43. *************************** 7. row ***************************
    44. Engine: ARCHIVE
    45. Support: YES
    46. Comment: Archive storage engine
    47. Transactions: NO
    48. XA: NO
    49. Savepoints: NO
    50. *************************** 8. row ***************************
    51. Engine: PERFORMANCE_SCHEMA
    52. Support: YES
    53. Comment: Performance Schema
    54. Transactions: NO
    55. XA: NO
    56. Savepoints: NO
    57. *************************** 9. row ***************************
    58. Engine: FEDERATED
    59. Support: NO
    60. Comment: Federated MySQL storage engine
    61. Transactions: NULL
    62. XA: NULL
    63. Savepoints: NULL
    64. 9 rows in set (0.00 sec)

    下面的表格对MySQL几种常用的数据引擎进行了简单的对比。

    | 特性 | InnoDB | MRG_MYISAM | MEMORY | MyISAM | | —————— | —————— | ————— | ——— | ——— | | 存储限制 | 有 | 没有 | 有 | 有 | | 事务 | 支持 | | | | | 锁机制 | 行锁 | 表锁 | 表锁 | 表锁 | | B树索引 | 支持 | 支持 | 支持 | 支持 | | 哈希索引 | | | 支持 | | | 全文检索 | 支持(5.6+) | | | 支持 | | 集群索引 | 支持 | | | | | 数据缓存 | 支持 | | 支持 | | | 索引缓存 | 支持 | 支持 | 支持 | 支持 | | 数据可压缩 | | | | 支持 | | 内存使用 | 高 | 低 | 中 | 低 | | 存储空间使用 | 高 | 低 | | 低 | | 批量插入性能 | 低 | 高 | 高 | 高 | | 是否支持外键 | 支持 | | | |

    通过上面的比较我们可以了解到,InnoDB是唯一能够支持外键、事务以及行锁的存储引擎,所以我们之前说它更适合互联网应用,而且它也是较新的MySQL版本中默认使用的存储引擎。

  • 在定义表结构为每个字段选择数据类型时,如果不清楚哪个数据类型更合适,可以通过MySQL的帮助系统来了解每种数据类型的特性、数据的长度和精度等相关信息。

    1. ? data types
    1. You asked for help about help category: "Data Types"
    2. For more information, type 'help <item>', where <item> is one of the following
    3. topics:
    4. AUTO_INCREMENT
    5. BIGINT
    6. BINARY
    7. BIT
    8. BLOB
    9. BLOB DATA TYPE
    10. BOOLEAN
    11. CHAR
    12. CHAR BYTE
    13. DATE
    14. DATETIME
    15. DEC
    16. DECIMAL
    17. DOUBLE
    18. DOUBLE PRECISION
    19. ENUM
    20. FLOAT
    21. INT
    22. INTEGER
    23. LONGBLOB
    24. LONGTEXT
    25. MEDIUMBLOB
    26. MEDIUMINT
    27. MEDIUMTEXT
    28. SET DATA TYPE
    29. SMALLINT
    30. TEXT
    31. TIME
    32. TIMESTAMP
    33. TINYBLOB
    34. TINYINT
    35. TINYTEXT
    36. VARBINARY
    37. VARCHAR
    38. YEAR DATA TYPE
    1. ? varchar
    1. Name: 'VARCHAR'
    2. Description:
    3. [NATIONAL] VARCHAR(M) [CHARACTER SET charset_name] [COLLATE
    4. collation_name]
    5. A variable-length string. M represents the maximum column length in
    6. characters. The range of M is 0 to 65,535. The effective maximum length
    7. of a VARCHAR is subject to the maximum row size (65,535 bytes, which is
    8. shared among all columns) and the character set used. For example, utf8
    9. characters can require up to three bytes per character, so a VARCHAR
    10. column that uses the utf8 character set can be declared to be a maximum
    11. of 21,844 characters. See
    12. http://dev.mysql.com/doc/refman/5.7/en/column-count-limit.html.
    13. MySQL stores VARCHAR values as a 1-byte or 2-byte length prefix plus
    14. data. The length prefix indicates the number of bytes in the value. A
    15. VARCHAR column uses one length byte if values require no more than 255
    16. bytes, two length bytes if values may require more than 255 bytes.
    17. *Note*:
    18. MySQL follows the standard SQL specification, and does not remove
    19. trailing spaces from VARCHAR values.
    20. VARCHAR is shorthand for CHARACTER VARYING. NATIONAL VARCHAR is the
    21. standard SQL way to define that a VARCHAR column should use some
    22. predefined character set. MySQL uses utf8 as this predefined character
    23. set. http://dev.mysql.com/doc/refman/5.7/en/charset-national.html.
    24. NVARCHAR is shorthand for NATIONAL VARCHAR.
    25. URL: http://dev.mysql.com/doc/refman/5.7/en/string-type-overview.html

    在数据类型的选择上,保存字符串数据通常都使用VARCHAR和CHAR两种类型,前者通常称为变长字符串,而后者通常称为定长字符串;对于InnoDB存储引擎,行存储格式没有区分固定长度和可变长度列,因此VARCHAR类型好CHAR类型没有本质区别,后者不一定比前者性能更好。如果要保存的很大字符串,可以使用TEXT类型;如果要保存很大的字节串,可以使用BLOB(二进制大对象)类型。在MySQL中,TEXT和BLOB又分别包括TEXT、MEDIUMTEXT、LONGTEXT和BLOB、MEDIUMBLOB、LONGBLOB三种不同的类型,它们主要的区别在于存储数据的最大大小不同。保存浮点数可以用FLOAT或DOUBLE类型,而保存定点数应该使用DECIMAL类型。如果要保存时间日期,DATETIME类型优于TIMESTAMP类型,因为前者能表示的时间日期范围更大。

DML(数据操作语言)

  1. use school;
  2. -- 插入学院数据
  3. insert into `tb_college`
  4. (`col_name`, `col_intro`)
  5. values
  6. ('计算机学院', '计算机学院1958年设立计算机专业,1981年建立计算机科学系,1998年设立计算机学院,2005年5月,为了进一步整合教学和科研资源,学校决定,计算机学院和软件学院行政班子合并统一运作、实行教学和学生管理独立运行的模式。 学院下设三个系:计算机科学与技术系、物联网工程系、计算金融系;两个研究所:图象图形研究所、网络空间安全研究院(2015年成立);三个教学实验中心:计算机基础教学实验中心、IBM技术中心和计算机专业实验中心。'),
  7. ('外国语学院', '外国语学院设有7个教学单位,6个文理兼收的本科专业;拥有1个一级学科博士授予点,3个二级学科博士授予点,5个一级学科硕士学位授权点,5个二级学科硕士学位授权点,5个硕士专业授权领域,同时还有2个硕士专业学位(MTI)专业;有教职员工210余人,其中教授、副教授80余人,教师中获得中国国内外名校博士学位和正在职攻读博士学位的教师比例占专任教师的60%以上。'),
  8. ('经济管理学院', '经济学院前身是创办于1905年的经济科;已故经济学家彭迪先、张与九、蒋学模、胡寄窗、陶大镛、胡代光,以及当代学者刘诗白等曾先后在此任教或学习。');
  9. -- 插入学生数据
  10. insert into `tb_student`
  11. (`stu_id`, `stu_name`, `stu_sex`, `stu_birth`, `stu_addr`, `col_id`)
  12. values
  13. (1001, '杨过', 1, '1990-3-4', '湖南长沙', 1),
  14. (1002, '任我行', 1, '1992-2-2', '湖南长沙', 1),
  15. (1033, '王语嫣', 0, '1989-12-3', '四川成都', 1),
  16. (1572, '岳不群', 1, '1993-7-19', '陕西咸阳', 1),
  17. (1378, '纪嫣然', 0, '1995-8-12', '四川绵阳', 1),
  18. (1954, '林平之', 1, '1994-9-20', '福建莆田', 1),
  19. (2035, '东方不败', 1, '1988-6-30', null, 2),
  20. (3011, '林震南', 1, '1985-12-12', '福建莆田', 3),
  21. (3755, '项少龙', 1, '1993-1-25', null, 3),
  22. (3923, '杨不悔', 0, '1985-4-17', '四川成都', 3);
  23. -- 插入老师数据
  24. insert into `tb_teacher`
  25. (`tea_id`, `tea_name`, `tea_title`, `col_id`)
  26. values
  27. (1122, '张三丰', '教授', 1),
  28. (1133, '宋远桥', '副教授', 1),
  29. (1144, '杨逍', '副教授', 1),
  30. (2255, '范遥', '副教授', 2),
  31. (3366, '韦一笑', default, 3);
  32. -- 插入课程数据
  33. insert into `tb_course`
  34. (`cou_id`, `cou_name`, `cou_credit`, `tea_id`)
  35. values
  36. (1111, 'Python程序设计', 3, 1122),
  37. (2222, 'Web前端开发', 2, 1122),
  38. (3333, '操作系统', 4, 1122),
  39. (4444, '计算机网络', 2, 1133),
  40. (5555, '编译原理', 4, 1144),
  41. (6666, '算法和数据结构', 3, 1144),
  42. (7777, '经贸法语', 3, 2255),
  43. (8888, '成本会计', 2, 3366),
  44. (9999, '审计学', 3, 3366);
  45. -- 插入选课数据
  46. insert into `tb_record`
  47. (`sid`, `cid`, `sel_date`, `score`)
  48. values
  49. (1001, 1111, '2017-09-01', 95),
  50. (1001, 2222, '2017-09-01', 87.5),
  51. (1001, 3333, '2017-09-01', 100),
  52. (1001, 4444, '2018-09-03', null),
  53. (1001, 6666, '2017-09-02', 100),
  54. (1002, 1111, '2017-09-03', 65),
  55. (1002, 5555, '2017-09-01', 42),
  56. (1033, 1111, '2017-09-03', 92.5),
  57. (1033, 4444, '2017-09-01', 78),
  58. (1033, 5555, '2017-09-01', 82.5),
  59. (1572, 1111, '2017-09-02', 78),
  60. (1378, 1111, '2017-09-05', 82),
  61. (1378, 7777, '2017-09-02', 65.5),
  62. (2035, 7777, '2018-09-03', 88),
  63. (2035, 9999, '2019-09-02', null),
  64. (3755, 1111, '2019-09-02', null),
  65. (3755, 8888, '2019-09-02', null),
  66. (3755, 9999, '2017-09-01', 92);

DQL(数据查询语言)

  1. -- 查询所有学生的所有信息
  2. select * from tb_student;
  3. select stu_id, stu_name, stu_sex, stu_birth, stu_addr, col_id from tb_student;
  4. -- 查询所有课程名称及学分(投影和别名)
  5. select cou_name as 课程名称, cou_credit as 学分 from tb_course;
  6. -- 查询所有女学生的姓名和出生日期(筛选)
  7. select stu_name, stu_birth from tb_student where stu_sex=0;
  8. -- 查询所有80后学生的姓名、性别和出生日期(筛选)
  9. select stu_name, stu_sex, stu_birth from tb_student
  10. where stu_birth>='1980-1-1' and stu_birth<='1989-12-31';
  11. select stu_name, stu_sex, stu_birth from tb_student
  12. where stu_birth between '1980-1-1' and '1989-12-31';
  13. -- 补充1:在查询时可以对列的值进行处理
  14. select
  15. stu_name as 姓名,
  16. case stu_sex when 1 then '男' else '女' end as 性别,
  17. stu_birth as 生日
  18. from tb_student
  19. where stu_birth between '1980-1-1' and '1989-12-31';
  20. -- 补充2MySQL方言(使用数据库特有的函数)
  21. -- 例如:Oracle中做同样事情的函数叫做decode
  22. select
  23. stu_name as 姓名,
  24. if(stu_sex, '男', '女') as 性别,
  25. stu_birth as 生日
  26. from tb_student
  27. where stu_birth between '1980-1-1' and '1989-12-31';
  28. -- 查询所有80后女学生的姓名和出生日期
  29. select stu_name, stu_birth from tb_student
  30. where stu_birth between '1980-1-1' and '1989-12-31' and stu_sex=0;
  31. -- 查询所有的80后学生或女学生的姓名和出生日期
  32. select stu_name, stu_birth from tb_student
  33. where stu_birth between '1980-1-1' and '1989-12-31' or stu_sex=0;
  34. -- 查询姓“杨”的学生姓名和性别(模糊)
  35. -- SQL中通配符%可以匹配零个或任意多个字符
  36. select stu_name, stu_sex from tb_student where stu_name like '杨%';
  37. -- 查询姓“杨”名字两个字的学生姓名和性别(模糊)
  38. -- SQL中通配符_可以刚刚好匹配一个字符
  39. select stu_name, stu_sex from tb_student where stu_name like '杨_';
  40. -- 查询姓“杨”名字三个字的学生姓名和性别(模糊)
  41. select stu_name, stu_sex from tb_student where stu_name like '杨__';
  42. -- 查询名字中有“不”字或“嫣”字的学生的姓名(模糊)
  43. -- 提示:前面带%的模糊查询性能基本上都是非常糟糕的
  44. select stu_name from tb_student
  45. where stu_name like '%不%' or stu_name like '%嫣%';
  46. update tb_student set stu_name='岳不嫣' where stu_id=1572;
  47. -- 并集运算
  48. select stu_name from tb_student where stu_name like '%不%'
  49. union
  50. select stu_name from tb_student where stu_name like '%嫣%';
  51. select stu_name from tb_student where stu_name like '%不%'
  52. union all
  53. select stu_name from tb_student where stu_name like '%嫣%';
  54. -- 正则表达式模糊查询
  55. select stu_name, stu_sex from tb_student where stu_name regexp '^杨.{2}$';
  56. -- 查询没有录入家庭住址的学生姓名(空值)
  57. -- null作任何运算结果也是产生nullnull相当于是条件不成立
  58. select stu_name from tb_student where stu_addr is null;
  59. select stu_name from tb_student where stu_addr<=>null;
  60. -- 查询录入了家庭住址的学生姓名(空值)
  61. select stu_name from tb_student where stu_addr is not null;
  62. -- 查询学生选课的所有日期(去重)
  63. select distinct sel_date from tb_record;
  64. -- 查询学生的家庭住址(去重)
  65. select distinct stu_addr from tb_student where stu_addr is not null;
  66. -- 查询男学生的姓名和生日按年龄从大到小排列(排序)
  67. -- asc - 升序(从小到大),desc - 降序(从大到小)
  68. select stu_name, stu_birth from tb_student
  69. where stu_sex=1 order by stu_birth asc;
  70. select stu_name, stu_birth from tb_student
  71. where stu_sex=1 order by stu_birth desc;
  72. -- 查询年龄最大的学生的出生日期(聚合函数) ---> 找出最小的生日
  73. select min(stu_birth) from tb_student;
  74. select
  75. min(stu_birth) as 生日,
  76. floor(datediff(curdate(), min(stu_birth))/365) as 年龄
  77. from tb_student;
  78. -- 查询年龄最小的学生的出生日期(聚合函数)
  79. select
  80. max(stu_birth) as 生日,
  81. floor(datediff(curdate(), max(stu_birth))/365) as 年龄
  82. from tb_student;
  83. -- 查询所有考试的平均成绩
  84. -- 聚合函数在遇到null值会做忽略的处理
  85. -- 如果做计数操作,建议使用count(*),这样才不会漏掉空值
  86. select avg(score) from tb_record;
  87. select sum(score) / count(score) from tb_record;
  88. select sum(score) / count(*) from tb_record;
  89. -- 查询课程编号为1111的课程的平均成绩(筛选和聚合函数)
  90. select avg(score) from tb_record where cid=1111;
  91. -- 查询学号为1001的学生所有课程的平均分(筛选和聚合函数)
  92. select avg(score) from tb_record where sid=1001;
  93. select count(distinct stu_addr) from tb_student where stu_addr is not null;
  94. -- 查询男女学生的人数(分组和聚合函数)
  95. -- SACSplit - Aggregate - Combine
  96. select
  97. if(stu_sex, '男', '女') as 性别,
  98. count(*) as 人数
  99. from tb_student group by stu_sex;
  100. -- 统计每个学院男女学生的人数
  101. select
  102. col_id as 学院,
  103. if(stu_sex, '男', '女') as 性别,
  104. count(*) as 人数
  105. from tb_student group by col_id, stu_sex;
  106. -- 查询每个学生的学号和平均成绩(分组和聚合函数)
  107. select
  108. sid as 学号,
  109. round(avg(score),1) as 平均分
  110. from tb_record group by sid;
  111. -- 查询平均成绩大于等于90分的学生的学号和平均成绩
  112. -- 分组以前的数据筛选使用where子句,分组以后的数据筛选使用having子句
  113. select
  114. sid as 学号,
  115. round(avg(score),1) as 平均分
  116. from tb_record
  117. group by sid having 平均分>=90;
  118. -- 查询年龄最大的学生的姓名(子查询)
  119. -- 嵌套查询:把一个查询的结果作为另外一个查询的一部分来使用。
  120. select stu_name from tb_student where stu_birth=(
  121. select min(stu_birth) from tb_student
  122. );
  123. -- 查询年龄最大的学生姓名和年龄(子查询+运算)
  124. select
  125. stu_name as 姓名,
  126. floor(datediff(curdate(), stu_birth) / 365) as 年龄
  127. from tb_student where stu_birth=(
  128. select min(stu_birth) from tb_student
  129. );
  130. -- 查询选了两门以上的课程的学生姓名(子查询/分组条件/集合运算)
  131. select stu_name from tb_student where stu_id in (
  132. select sid from tb_record group by sid having count(*)>2
  133. );
  134. -- 查询课程的名称、学分和授课老师的姓名(连接查询)
  135. select cou_name, cou_credit, tea_name
  136. from tb_course, tb_teacher
  137. where tb_course.tea_id=tb_teacher.tea_id;
  138. select cou_name, cou_credit, tea_name from tb_course t1
  139. inner join tb_teacher t2 on t1.tea_id=t2.tea_id;
  140. -- 查询学生姓名、课程名称以及成绩(连接查询)
  141. select stu_name, cou_name, score
  142. from tb_record, tb_student, tb_course
  143. where stu_id=sid and cou_id=cid and score is not null;
  144. select stu_name, cou_name, score from tb_student
  145. inner join tb_record on stu_id=sid
  146. inner join tb_course on cou_id=cid
  147. where score is not null;
  148. -- 查询选课学生的姓名和平均成绩(子查询和连接查询)
  149. select stu_name, avg_score
  150. from tb_student, (select sid, round(avg(score),1) as avg_score
  151. from tb_record group by sid
  152. ) tb_temp where stu_id=sid;
  153. -- 查询每个学生的姓名和选课数量(左外连接和子查询)
  154. select
  155. stu_name as 姓名,
  156. ifnull(total, 0) as 选课数量
  157. from tb_student left outer join (
  158. select sid, count(*) as total from tb_record group by sid
  159. ) tb_temp on stu_id=sid;

上面的DML有几个地方需要加以说明:

  1. MySQL中支持多种类型的运算符,包括:算术运算符(+、-、*、/、%)、比较运算符(=、<>、<=>、<、<=、>、>=、BETWEEN…AND…、IN、IS NULL、IS NOT NULL、LIKE、RLIKE、REGEXP)、逻辑运算符(NOT、AND、OR、XOR)和位运算符(&、|、^、~、>>、<<),我们可以在DML中使用这些运算符处理数据。

  2. 在查询数据时,可以在SELECT语句及其子句(如WHERE子句、ORDER BY子句、HAVING子句等)中使用函数,这些函数包括字符串函数、数值函数、时间日期函数、流程函数等,如下面的表格所示。

    常用字符串函数。

    | 函数 | 功能 | | ———————————- | ——————————————————————————- | | CONCAT | 将多个字符串连接成一个字符串 | | FORMAT | 将数值格式化成字符串并指定保留几位小数 | | FROM_BASE64 / TO_BASE64 | BASE64解码/编码 | | BIN / OCT / HEX | 将数值转换成二进制/八进制/十六进制字符串 | | LOCATE | 在字符串中查找一个子串的位置 | | LEFT / RIGHT | 返回一个字符串左边/右边指定长度的字符 | | LENGTH / CHAR_LENGTH | 返回字符串的长度以字节/字符为单位 | | LOWER / UPPER | 返回字符串的小写/大写形式 | | LPAD / RPAD | 如果字符串的长度不足,在字符串左边/右边填充指定的字符 | | LTRIM / RTRIM | 去掉字符串前面/后面的空格 | | ORD / CHAR | 返回字符对应的编码/返回编码对应的字符 | | STRCMP | 比较字符串,返回-1、0、1分别表示小于、等于、大于 | | SUBSTRING | 返回字符串指定范围的子串 |

    常用数值函数。

    | 函数 | 功能 | | ————————————————————— | ————————————————— | | ABS | 返回一个数的绝度值 | | CEILING / FLOOR | 返回一个数上取整/下取整的结果 | | CONV | 将一个数从一种进制转换成另一种进制 | | CRC32 | 计算循环冗余校验码 | | EXP / LOG / LOG2 / LOG10 | 计算指数/对数 | | POW | 求幂 | | RAND | 返回[0,1)范围的随机数 | | ROUND | 返回一个数四舍五入后的结果 | | SQRT | 返回一个数的平方根 | | TRUNCATE | 截断一个数到指定的精度 | | SIN / COS / TAN / COT / ASIN / ACOS / ATAN | 三角函数 |

    常用时间日期函数。

    | 函数 | 功能 | | ———————————- | ——————————————————- | | CURDATE / CURTIME / NOW | 获取当前日期/时间/日期和时间 | | ADDDATE / SUBDATE | 将两个日期表达式相加/相减并返回结果 | | DATE / TIME | 从字符串中获取日期/时间 | | YEAR / MONTH / DAY | 从日期中获取年/月/日 | | HOUR / MINUTE / SECOND | 从时间中获取时/分/秒 | | DATEDIFF / TIMEDIFF | 返回两个时间日期表达式相差多少天/小时 | | MAKEDATE / MAKETIME | 制造一个日期/时间 |

    常用流程函数。

    | 函数 | 功能 | | ——— | ———————————————————————— | | IF | 根据条件是否成立返回不同的值 | | IFNULL | 如果为NULL则返回指定的值否则就返回本身 | | NULLIF | 两个表达式相等就返回NULL否则返回第一个表达式的值 |

    其他常用函数。

    | 函数 | 功能 | | ——————————— | ——————————————- | | MD5 / SHA1 / SHA2 | 返回字符串对应的哈希摘要 | | CHARSET / COLLATION | 返回字符集/校对规则 | | USER / CURRENT_USER | 返回当前用户 | | DATABASE | 返回当前数据库名 | | VERSION | 返回当前数据库版本 | | FOUND_ROWS / ROW_COUNT | 返回查询到的行数/受影响的行数 | | LAST_INSERT_ID | 返回最后一个自增主键的值 | | UUID / UUID_SHORT | 返回全局唯一标识符 |

DCL(数据控制语言)

  1. -- 创建可以远程登录的root账号并为其指定口令
  2. create user 'root'@'%' identified by '123456';
  3. -- 为远程登录的root账号授权操作所有数据库所有对象的所有权限并允许其将权限再次赋予其他用户
  4. grant all privileges on *.* to 'root'@'%' with grant option;
  5. -- 创建名为hellokitty的用户并为其指定口令
  6. create user 'hellokitty'@'%' identified by '123123';
  7. -- 将对school数据库所有对象的所有操作权限授予hellokitty
  8. grant all privileges on school.* to 'hellokitty'@'%';
  9. -- 召回hellokittyschool数据库所有对象的insert/delete/update权限
  10. revoke insert, delete, update on school.* from 'hellokitty'@'%';

说明:创建一个可以允许任意主机登录并且具有超级管理员权限的用户在现实中并不是一个明智的决定,因为一旦该账号的口令泄露或者被破解,数据库将会面临灾难级的风险。