学习笔记——mysql(CRUD)

一、学习重点

二、学习内容

需求1

-- 1.查询'01'号学生的姓名和各科成绩 **
SELECT
	s.id sid,
	s.`name` sname,
	c.`name` cname,
	sc.score 
FROM
	student s
	LEFT JOIN scores sc ON s.id = sc.s_id
	LEFT JOIN course c ON c.id = sc.c_id 
WHERE
	s.id = 1;
-- 2.查询各个学科的平均成绩和最高成绩**
SELECT
	c.id,
	c.`name`,
	AVG( sc.score ),
	max( sc.score ) 
FROM
	course c
	LEFT JOIN scores sc ON c.id = sc.c_id 
GROUP BY
	c.id,
	c.`name`;
-- 3.查询每个同学的最高成绩和科目名称****(明天说,子查询)
-- 4.查询所有姓张的同学的各科成绩**
SELECT
	s.id,
	s.`name`,
	c.`name` cname,
	sc.score 
FROM
SELECT
	s.id,
	s.`name`,
	c.`name` cname,
	sc.score 
FROM
	student s
	LEFT JOIN scores sc ON sc.s_id = s.id
	LEFT JOIN course c ON c.id = sc.c_id 
WHERE
	s.`name` LIKE '张%';
-- 5.查询每个课程的最高分的学生信息*****(明天说,子查询)

需求2

-- 6.查询名字中含有'张'或'李'字的学生的信息和各科成绩。
-- 7.查询平均成绩及格的同学的信息。(子查询)
-- 8.将学生按照总分数进行排名。(从高到低)
-- 9.查询数学成绩的最高分、最低分、平均分。
-- 10.将各科目按照平均分排序。

三、笔记内容

Mysql数据库

数据库

  • 数据库【按照数据结构来组织、存储和管理数据的仓库】。是一个长期存储在计算机内的、有组织的、可共享的、统一管理的大量数据的集合。
  • 数据对于公司来说最宝贵的财富,程序员的工作就是对数据进行管理,包括运算、流转、存储、展示等,数据库最重要的功能就是【存储数据】,长期保存数据。

Mysql

  • MySQL是一个【关系型数据库管理系统】,瑞典的公司研发,被【Oracle】收购。
  • MySQL使用了一种语言【SQL语言】。
  • MySQL分为社区版和商业版,体积小、速度快、成本低,开源。

基本操作

MySQL保存数据的模式:

  1. 创建一个数据库。
  2. 在数据库下保存多张表。
  3. 在每张表中保存多条数据。

登录mysql:

mysql -h 127.0.0.1 -p3306 -uroot -p

MySQL是一个数据库管理系统,管理多个数据库。

创建一个数据库:

create database 数据库名;
create schema 数据库名;

查看所有的数据库:

show databases;

使用数据库:

use 数据库名;

用来存储数据的对象,是有结构的数据的集合。

  • 行:一行即为一条数据,数据库一共有多少条数据,实际上就是有几行数据。
  • 列:一列即为一个字段,数据库一共有多少个字段,实际上就是有几列数据。

SQL语言

SQL是一种特殊目的的编程语言,是一种数据库查询和程序设计语言,用于存储数据以及查询、更新和管理关系型数据库系统。

SQL分类

  • DCL(Data Control Language):数据控制语言,用来定义访问权限和安全级别。
  • DDL(Data Definition Language):数据定义语言,用来定义数据库对象:库,表,字段(列)。功能:创建、删除、修改库和表结构。
  • DML(Data Manipulation Language):数据操作语言,用来定义数据的增删改记录。
  • DQL(Data Query Language):数据库查询语言,用来查询记录。
  • TCL(Transition Control Language):事务控制语言,用来管理事务。

DCL(数据库控制语言)

创建用户

创建一个用户,该用户只能在指定的ip地址上登录mysql:

create user 用户名@IP地址 identified by '密码';

创建一个用户,该用户可以在任意ip地址上登录mysql:

create user 'moon'@'%' identified by 'root';

修改密码:

-- 5.7版本需要使用passwod对密码进行加密
set password for moon@'%' = password('新密码');
-- 8.0版本直接赋值
set password for moon@'%' = '新密码';

给用户授权

指定用户指定数据库上赋予指定权限,权限有很多,列举几个常用的:

  • create:可以创建数据库
  • select:查询数据
  • delete:删除数据
  • update:修改数据
  • insert:插入数据
-- 语法:grant `权限1,权限2,....权限n` on 数据库名.* to 用户名@IP地址
grant select,insert,update,delete,create on `jsoft`.`user` to `moon`@`%`;

注意:这里用的是着重符,不是单引号。

撤销授权

-- 语法:revoke 权限1,....权限n on 数据库.* from 用户名@IP地址
revoke all on `jsoft`.* from `moon`@`%`;

查看权限

查看指定用户的权限

-- 语法:show grants for 用户名@IP地址
show grants for 'moon'@'%';

删除用户

-- 语法:drop user 用户名@IP地址
drop user 'moon'@'%';

DDL(数据定义语言)

DDL主要是用在定义或改变表的结构。

创建表

create table 表名(
	字段名1(列名) 类型(长度) 约束条件,
    字段名2(列名) 类型(长度) 约束条件,
    字段名3(列名) 类型(长度) 约束条件,
    .......
);

在关系型数据库中,我们需要这顶表名和列名,同时设定。

数据类型

整型
MySQL数据类型 含义
tinyint 1字节,范围(-128~127)
smallint 2字节,范围(-3W多~3W多)
mediumint 3字节,范围
int 4字节,范围(-21个亿~21个亿)
bigint 8字节,非常大

在整型中,我们默认使用的是【有符号】的,我们可以使用unsigned关键字,定义成无符号类型,tinyint unsigned的取值范围0~255

如果长度需要配合zerofill

int(4) unsigned zerofill;

说明:上述的int长度为4,如果设置了zerofill,如果数据是1,最终存到表格中的数据格式为0001,0010。

浮点型
MySQL数据类型 含义
float(m,d) 4字节,单精度浮点型,m总长度,d小数位。
double(m,d) 8字节,双精度浮点型,m总长度,d小数位。
decimal(m,d) decimal是存储为字符串的浮点数,对应我们java中的BigDecimal。

比如定义一个float(5,3):

  • 插入123.45678,最后查询得到的结果就是99.999;
  • 插入12.3456789,最后查询得到的结果就是12.346;

所以,在使用浮点型的时候,要以插入到数据库中的实际结果为准。

字符串类型
MySQL数据类型 含义
char(n) 固定长度,最多255个字符。
varchar(n) 可变长度,最多65535个字符。
tinytext 可变长度,最大255个字节。
text 可变长度,最大65535个字节。
mediumtext 可变长度,最大16MB。
longtext 可变长度,最大4GB。

(1)char和vachar的区别:

  • char类型是【定长】的类型,当定义char(10),输入的时"123",他们占用的空间依然是10个字符。当输入的字符如果超出指定的范围,char会截取超出的字符。而且,当存储char,MySQL会自动删除输入字符串末尾的空格。
  • char适合存储很短的,一般固定长度的字符串。例如,char非常适合存储密码MD5值,因为它是一个定长的值。对于端的列,char比varchar在存储空间上效率更高。
  • varchar(n)类型用来存储可变长度,长度最大为n个字符的可变长度的字符串数据。比如varchar(10),然后存储"abc",实际就是存储了3个字符。
  • char类型每次修改的数据长度相同,效率更高。varchar,每次修改的数据长度如果不同,效率更低。

(2)varchar和text区别:

  • text不能设置默认值,varchar可以设置默认值。
  • text类型,由于单表的最大行宽的限制,支持溢出存储,只会存放768字节在数据页中,剩余的数据存储在溢出段中。
  • 一般我们都是用varchar。
日期类型
MySQL数据类型 含义
date 3字节,日期,格式:2022-08-15
time 3字节,时间,格式:10:54:30
datatime 8字节,日期时间,格式:2022-08-15 10:55:40
timestamp 4字节,时间戳,毫秒数。
year 1字节,年份

建表约束

因为一张表要有多个列,数据库中的表不止有一张,建表约束说的就是我们 应该如何规范表中的数据以及表之间的关系。

MySQL约束类型:

约束名称 描述
NOT NULL 非空约束
UNIQUE 唯一约束,取值不允许重复
PRIMARY KEY 主键约束(主关键字),自带非空,唯一、索引
DEFAULT 默认值
FOREIGH KEY 外键约束,表和表之间的约束

(1)NOT NULL约束

CREATE TABLE `student` (
	`stu_id` int,
	`stu_name` VARCHAR(50) NOT NULL,
	`gender` char(1) DEFAULT '男',
	`brithday` datetime,
	PRIMARY KEY(stu_id)
);

(2)UNIQUE约束

create table `book` (
	`id` int PRIMARY KEY auto_increment,
	`name` varchar(50) not null,
	`bar_code` VARCHAR(30) not null,
	`aut_id` int not null,
	UNIQUE(bar_code)
);

(3)主键约束

用多个列来共同当主键:

create table `authors`(
	`aut_id` int,
	`aut_name` varchar(50) not null,
	`gender` char(1) default '男',
	`country` varchar(50),
	`birthday` datetime,
	PRIMARY KEY(aut_id,aut_name)
);

(4)外键约束

推荐配合主键去使用。有了这个约束,我们在向表中插入数据时,来源于另外一张表的主键

外键会产生的效果:

  1. 删除表的时候,如果不删除引用外键的表,被引用的表是不能直接删除。
  2. 外键的值必须来源于引用的表的主键字符。
create table `author`(
	`aut_id` int,
	`aut_name` varchar(50) not null,
	`gender` char(1) default '男',
	`country` varchar(50),
	`birthday` datetime,
	PRIMARY KEY(aut_id)
);
create table `book` (
	`id` int PRIMARY KEY auto_increment,
	`name` varchar(50) not null,
	`bar_code` VARCHAR(30) not null UNIQUE,
	`aut_id` int not null,
	FOREIGN KEY(aut_id) REFERENCES author(aut_id)
);

在创建表的时候,建议字段名(表名)使用着重符。

对表的修改操作

查看当前库中的是所有表:

show tables;

查看表结构:

desc 表名;

修改表有5个操作,但是前缀都是一样的 alter table 表名 ...

  • 添加列

    ALTER TABLE authors ADD ( hobby VARCHAR ( 20 ), address VARCHAR ( 50 ) );
    
  • 修改列数据类型

    ALTER table author MODIFY address varchar(100);
    
  • 修改列名称和数据类型

    alter table author change address addr VARCHAR(60);
    
  • 删除列

    alter table author drop addr;
    
  • 修改表名

    ALTER TABLE author RENAME `authors`;
    
  • 删除表

    drop table if EXISTS `user`;
    
  • 添加主键

    alter table 表名 ADD CONSTRAINT 主键名(pk_表名) primary key 表名(字段名);
    
    ALTER TABLE `authors` ADD CONSTRAINT pk_authors PRIMARY KEY `authors` ( aut_id );
    
  • 添加外键

    alter table 从表 add constraint 外键名(fk_从表_主表) foreign key 从表(外键字段) REFERENCES 主表(主键字段;)
    
    ALTER TABLE book ADD CONSTRAINT fk_book_authors FOREIGN KEY book ( aut_id ) REFERENCES `authors` ( aut_id );
    

DML(数据操作语言)

该语言来对表记录进行操作(增、删、改),不包含查询。

插入数据

INSERT INTO `authors` ( aut_id, aut_name, gender, country, birthday, hobby ) VALUES (4,'斯蒂芬·威廉·霍金','男','英国','1942-1-8','物理学');

如果插入的是全字段,字段名可以省略。

INSERT INTO `author` VALUES (5,'余华','男','中国','1960-4-3','写作');

说明:

​ 1、在数据库中所有的字符串类型,必须使用引号。

​ 2、如果部分字段插入,必须列名和值要匹配。如果全字段插入,则列名可以省略。

批量插入。/

INSERT INTO `authors` VALUES 
(7,"余秋雨",'男','中国','1946-8-23','写作','address'),
(8,"刘慈欣",'男','中国','1963-6-23','写作','address');

修改数据

修改某列的全部的值:

update `authors` set aut_name = '理察·弗拉纳根',country='澳大利亚';

修改特定行的数据:

update `authors` set aut_name = '马识途',country='中国' where aut_id = 1;

where是一个关键字,我们可以使用where关键字实现丰富的筛选,它很像我们的if语句,可以使用各种复杂的条件运算:

  • =(没有==,也没有equals)
  • !=
  • >
    • where aut_id > 1
  • <
  • >=
  • <=
  • <> 不等于
  • between...and
    • where aut_id between 1 and 4
    • where aut_id > 1 and aut_name='xxx'
  • in(....)
    • where aut_id in(1,3,5)
  • is null
    • where name is null
  • not
    • where name is not null
  • or
  • and

删除数据

全部删除:

delete from `student`;

根据条件删除:

delete from `authors` where aut_id = 8;

说明:通过delete这种删除方式删除的数据,主键如果是自动递增,会断档。

截断(清空表):

TRUNCATE student;

说明:

truncate实际上应该属于DDL语言,操作立即生效,不能撤回。

  • truncate和delete都是删除数据,drop删除整个表。
  • truncate速度快,效率高,可以理解为直接删除整个表,再重新建立。
  • truncate和delete都不会是表结构及其列、约束、索引的发生改变。

DQL (数据库查询语言)

重点,DQL是我们每天都要接触编写也是最难的SQL,该语言用来查询记录,不会修改数据库和表结构。

构建数据库

创建一张学生表

DROP TABLE IF EXISTS student;

CREATE TABLE student(
	`id` INT(10) PRIMARY KEY,
	`name` VARCHAR(10),
	`age` INT(10) NOT NULL,
	gender VARCHAR(2)
);

创建一张课程表

DROP TABLE IF EXISTS course;

CREATE TABLE course(
	id INT(10) PRIMARY KEY,
	`name` VARCHAR(10),
	`t_id` INT(10) 
);

创建一张老师表

DROP TABLE IF EXISTS teacher;

CREATE TABLE teacher(
	id INT(10) PRIMARY KEY,
	`name` VARCHAR(10)
);

创建一张分数表

DROP TABLE IF EXISTS scores;

CREATE TABLE scores(
	s_id INT(10),
	score int(10),
	c_id INT(10),
	PRIMARY KEY(s_id,c_id)
);

表格填充数据

insert into  student (id,name,age,gender)VALUES(1,'小明',19,'男'),(2,'小红',19,'男'),(3,'小刚',24,'男'),(4,'小龙',11,'男'),(5,'小丽',18,'男'),(6,'小军',18,'女'),(7,'小航',16,'男'),(8,'小亮',23,'男'),(9,'小杰',22,'女'),(10,'小虎',21,'男');

insert into  course (id,name,t_id)VALUES(1,'数学',1),(2,'语文',2),(3,'c++',3),(4,'java',4),(5,'php',null);


insert into  teacher (id,name)VALUES(1,'Tom'),(2,'Jerry'),(3,'Tony'),(4,'Jack'),(5,'Rose');


insert into  scores (s_id,score,c_id)VALUES(1,80,1);
insert into  scores (s_id,score,c_id)VALUES(1,56,2);
insert into  scores (s_id,score,c_id)VALUES(1,95,3);
insert into  scores (s_id,score,c_id)VALUES(1,30,4);
insert into  scores (s_id,score,c_id)VALUES(1,76,5);

insert into  scores (s_id,score,c_id)VALUES(2,35,1);
insert into  scores (s_id,score,c_id)VALUES(2,86,2);
insert into  scores (s_id,score,c_id)VALUES(2,45,3);
insert into  scores (s_id,score,c_id)VALUES(2,94,4);
insert into  scores (s_id,score,c_id)VALUES(2,79,5);

insert into  scores (s_id,score,c_id)VALUES(3,65,2);
insert into  scores (s_id,score,c_id)VALUES(3,85,3);
insert into  scores (s_id,score,c_id)VALUES(3,37,4);
insert into  scores (s_id,score,c_id)VALUES(3,79,5);

insert into  scores (s_id,score,c_id)VALUES(4,66,1);
insert into  scores (s_id,score,c_id)VALUES(4,39,2);
insert into  scores (s_id,score,c_id)VALUES(4,85,3);

insert into  scores (s_id,score,c_id)VALUES(5,66,2);
insert into  scores (s_id,score,c_id)VALUES(5,89,3);
insert into  scores (s_id,score,c_id)VALUES(5,74,4);


insert into  scores (s_id,score,c_id)VALUES(6,80,1);
insert into  scores (s_id,score,c_id)VALUES(6,56,2);
insert into  scores (s_id,score,c_id)VALUES(6,95,3);
insert into  scores (s_id,score,c_id)VALUES(6,30,4);
insert into  scores (s_id,score,c_id)VALUES(6,76,5);

insert into  scores (s_id,score,c_id)VALUES(7,35,1);
insert into  scores (s_id,score,c_id)VALUES(7,86,2);
insert into  scores (s_id,score,c_id)VALUES(7,45,3);
insert into  scores (s_id,score,c_id)VALUES(7,94,4);
insert into  scores (s_id,score,c_id)VALUES(7,79,5);

insert into  scores (s_id,score,c_id)VALUES(8,65,2);
insert into  scores (s_id,score,c_id)VALUES(8,85,3);
insert into  scores (s_id,score,c_id)VALUES(8,37,4);
insert into  scores (s_id,score,c_id)VALUES(8,79,5);

insert into  scores (s_id,score,c_id)VALUES(9,66,1);
insert into  scores (s_id,score,c_id)VALUES(9,39,2);
insert into  scores (s_id,score,c_id)VALUES(9,85,3);
insert into  scores (s_id,score,c_id)VALUES(9,79,5);

insert into  scores (s_id,score,c_id)VALUES(10,66,2);
insert into  scores (s_id,score,c_id)VALUES(10,89,3);
insert into  scores (s_id,score,c_id)VALUES(10,74,4);
insert into  scores (s_id,score,c_id)VALUES(10,79,5);

单表查询

基本查询
基本语法

查询所有列:

select * from 表名;
select * from student;

查询指定的列:

select id,`name`,age,gender from student;
select id,`name`,age from student;

补充:开发中,严禁使用select *.

如果表中有完全重复的记录只显示一次,在查询的列之前加上distinct.

select DISTINCT `name` from book;
列运算
select id,`name`,age/10 from student;

注意:我们写的所有的查询语句,最终执行的结果,都是生成一张虚拟表。

select id,`name`,sal+1000 from employee;

注意:

  1. null值和任何值做计算都为null,需要用到函数ifnull()函数。select IFNULL(sal,0) + 1000 from employee;如果薪资是空,则为0。
  2. 将字符串做加减乘除运算,会把字符串当0处理。
别名

我们可以给列起[别名],因为我们在查询过程中,列名很可能重复,可能名字不够简洁,或者列的名字不能满足我们的要求.

select id `编号`,`name` `姓名`,age `年龄`,gender `性别` from student;
select id as `编号`,`name` as `姓名`,age as `年龄`,gender as `性别` from student;

条件查询:在后面添加where指定条件

select * from student where id = 3;
select * from student where id in (1,3,5);
select * from student where id > 2;
select * from student where id BETWEEN 3 and 5;
select * from student where id BETWEEN 6 and 7 or age > 20;

模糊查询:我想查询所有姓张的。

select * from student where `name` like '张%';
select * from student where `name` like '张_';
select * from student where `name` like '%明%';
select * from student where `name` like '_明_';

通配符:_下划线代表一个字符,%百分号代表任意个字符。

排序
  • 升序

    select * from student ORDER BY age ASC;
    -- ASC是可以省略
    
  • 降序

    select * from student ORDER BY age DESC;
    
  • 使用多列作为排序条件:当第一个排序条件相同时,根据第二列排序条件进行排序(第二列如果还相同,.....)

    select * from student ORDER BY age asc,id desc;
    

举例:

创建一张用户表,id,username,password。

几乎所有的表都会有两个字段,create_time,update_time。

几乎所有的查询都会按照update_time降序排列。

聚合函数
count

查询满足条件的记录行数,后边可以跟where条件。

如果满足条件的列值为空,不会进行统计。

如果我们要统计真实有效的记录数,最好不要用可以为空列。

  • count(*)
  • count(主键)(推荐)
  • count(1)(不推荐)
select count(列名) from 表名;
select count(id) from student where gender='男';
max

查询满足条件的记录中的最大值,后面可以跟where条件。

select max(age) from student where gender='女';
min

查询满足条件的记录中的最小值,后面可以跟where条件。

select MIN(age) from student where gender='男';
sum

查询满足条件的记录的和,后面可以跟where条件。

select sum(age) from student where gender='男';
avg

查询满足条件的记录的平均数,后面可以跟where条件。

select avg(score) from scores where c_id = 3;
分组查询

顾名思义:分组查询就是将原有数据进行分组统计。

举例:

将班级的同学按照性别分组,统计男生和女生的平均年龄。

select 分组列名,聚合函数1,聚合函数2... from 表名 group by 该分组列名;

分组要使用关键词group by,后面可以是一列,也可以是多个列,分组后查询的列只能是分组的列,或者是使用了聚合函数的其他的列,剩余列不能单独使用。

-- 根据性别分组,查看每一组的平均年龄和最大年龄
select gender,avg(age),max(age) from student group by gender;
-- 根据专业号分组,查看每一个专业的平均分
select c_id,avg(score) from scores group by c_id;

我们可以这样理解:一旦发生了分组,我们查询的结果只能是所有男生的年龄平均值、最大值,而不能是某一个男生的数据。

分组查询前,可以通过关键字【where】先把满足条件的人分出来,再分组。

select 分组列,聚合函数1... from 表名 where 条件 group by 分组列;
select c_id,avg(score) from scores where c_id in (1,2,3) group by c_id;

分组查询后,也可以通过关键字【having】把组信息中满足条件的组再细分出来。

select 分组列,聚合函数1... from 表名 where 条件 group by 分组列 having 聚合函数或列名(条件);
select gender,avg(age),sum(age) `sum_age` from student GROUP BY gender HAVING `sum_age` > 50;

面试题:where和having的区别?

  1. where是写在group by之前的筛选,在分组前筛选;having是写在group by之后,分组后再筛选。
  2. where只能使用分组的列作为筛选条件;having既可以使用分组的列,也可以使用聚合函数列作为筛选条件。
分页查询

limit字句,用来限定查询结果的起始行,以及总行数。

limit是mysql独有的语法。

select * from student limit 4,3;
select * from student limit 4;
  • 如果只有一个参数,说明从起始位置查找4条记录。

  • 如果两个参数,说明从第4行下一行,向后查找3条记录。

面试题:

  • MySQL:limit
  • Oracle:rownum
  • SqlServer:top

分析:

student表中有10条数据,如果每页显示4条,分几页?3页

3页怎么来的?(int)(Math.ceil(10 / 4));

显示第一页的数据:select * from student limit 0,4;

第二页:select * from student limit 4,4;

第三页:select * from student limit 8,4;

一个问题:我想要判断在student表中有没有叫"小红"的这个人?

1.0版本

select * from student where name = '小红';
select id from student where name = '小红';

2.0版本

select count(id) from student where name = '小红';

3.0版本

select id from student where name = '小红' limit 1;

注意:Limit字句永远是在整个的sql语句的最后。

多表查询

笛卡尔积
select * from student,teacher;

如果两个表没有任何关联关系,我们也不会连接这两张表。

在一个select * from 表名1,表名2;,就会出现笛卡尔乘积,会生成一张虚拟表,这张虚拟表的数据就是表1和表2两张表数据的乘积。

注意:开发中,一定要避免出现笛卡尔积。

多表连接的方式有四种:

  • 内连接
  • 外连接**
  • 全连接
  • 子查询
SQL92语法

1992年的语法。

-- 查询学号,姓名,年龄,分数,通过多表连接查询,student和scores通过id和s_id连接
SELECT
	stu.id 学号,
	stu.name 姓名,
	stu.age 年龄,
	sc.score 分数 
FROM
	student stu,
	scores sc 
WHERE
	stu.id = sc.s_id;
-- 查询学号,姓名,年龄,分数,科目名称,通过多表查询,student和scores,course
SELECT
	stu.`id` 学号,
	stu.`name` 姓名,
	stu.`age` 年龄,
	sc.`score` 分数,
	c.`name` 科目
FROM
	student stu,
	scores sc,
	course c
WHERE
	stu.id = sc.s_id
AND
	c.id = sc.c_id;
-- 查询学号,姓名,年龄,分数,科目名称,老师名称,通过多表查询,student和scores,course,teacher
SELECT
	stu.`id` 学号,
	stu.`name` 姓名,
	stu.`age` 年龄,
	sc.`score` 分数,
	c.`name` 科目,
	t.`name` 老师
FROM
	student stu,
	scores sc,
	course c,
	teacher t
WHERE
	stu.id = sc.s_id
AND
	c.id = sc.c_id
AND
	c.t_id = t.id;
-- 查询老师的信息以及对应教的课程
SELECT
	t.id 教师号,
	t.NAME 教师姓名,
	c.NAME 科目名
FROM
	teacher t,
	course c 
WHERE
	t.id = c.t_id;

SQL92语法,多表查询,如果有数据为null,会过滤掉。

-- 查询学号,姓名,年龄,分数,科目名称,通过多表查询,student和scores,course
-- 在查询的基础上,进一步筛选,筛选小红和张小军的成绩
SELECT
	stu.`id` 学号,
	stu.`name` 姓名,
	stu.`age` 年龄,
	sc.`score` 分数,
	c.`name` 科目
FROM
	student stu,
	scores sc,
	course c
WHERE
	stu.id = sc.s_id
AND
	c.id = sc.c_id
AND
	stu.`name` in ('小红','张小军');
-- 查询学号,姓名,年龄,分数,科目名称,通过多表查询,student和scores,course
-- 在查询的基础上,进一步筛选,筛选小红和张小军的成绩
-- 在小红和张小军成绩的基础上进一步再筛选,筛选他们的java成绩
SELECT
	stu.`id` 学号,
	stu.`name` 姓名,
	stu.`age` 年龄,
	sc.`score` 分数,
	c.`name` 科目
FROM
	student stu,
	scores sc,
	course c
WHERE
	stu.id = sc.s_id
AND
	c.id = sc.c_id
AND
	stu.`name` in ('小红','张小军')
AND
	c.`name` = 'java';
-- 查询学号,姓名,年龄,分数,科目名称,通过多表查询,student和scores,course
-- 找出最低分和最高分,按照科目分组,每一科
SELECT
	sc.c_id,
	max( score ),
	min( score ),
	c.`name` 
FROM
	scores sc,
	course c 
WHERE
	sc.c_id = c.id 
GROUP BY
	sc.c_id;
SQL99语法

1999年的语法。

内连接

在我们刚才的sql当中,使用逗号分隔两张表进行查询,mysql进行优化默认就等效于内连接。

使用【join】关键字,使用【on】来确定连接条件。【where】只做筛选条件。

SELECT
	t.*,
	c.* ,
	sc.*
FROM
	teacher t
	INNER JOIN course c ON c.t_id = t.id
	INNER JOIN scores sc ON sc.c_id = c.id;
外连接(常用)

内连接和外连接的区别:

  • 对于【内连接】的两个表,如果【驱动表】在【被驱动表】找不到与之匹配的记录,则最终的记录不会出现在结果集中。
  • 对于【外连接】中的两个表,即使【驱动表】中的记录在【被驱动表】中找不到与之匹配的记录,也要将该记录加入到最后的结果集中。针对不同的【驱动表】的位置,有分为【左外连接】和【右外连接】。
  • 对于左连接,左边的表为主,左边的表的记录会完整的出现在结果集里。
  • 对于右连接,右边的表为主,左边的表的记录会完整的出现在结果集里。

外连接的关键字【outter join】,也可以省略outter,连接条件同样使用【on】关键字。

左连接

SELECT
	t.*,
	c.* 
FROM
	teacher t
	LEFT JOIN course c ON t.id = c.t_id;

右连接

SELECT
	t.*,
	c.* 
FROM
	course c
	RIGHT JOIN teacher t ON t.id = c.t_id;
全连接

mysql不支持全连接。oracle支持全连接。

SELECT
	* 
FROM
	teacher t
	FULL JOIN course c ON c.t_id = t.id;

我们可以通过一些手段来实现全连接的效果

SELECT
	t.*,
	c.* 
FROM
	teacher t
	LEFT JOIN course c ON t.id = c.t_id
UNION
SELECT
	t.*,
	c.* 
FROM
	teacher t
	RIGHT JOIN course c ON t.id = c.t_id
posted @   LJMMJL  阅读(45)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示