_多表查询
-
笛卡尔积:取A,B集合所有组合情况;
-
多表查询::从多张表查询数据
- 连接查询
- 内连接:相当于查询A、B交集的数据
- 外连接:
- 左外连接:相当于查询A表所有数据和交集部分数据
- 右外连接:相当于查询B表所有数据和交集部分数据
- 子查询
- 连接查询
-
/* 1. 笛卡尔积:取A,B集合所有组合情况; 2. 多表查询::从多张表查询数据 - 连接查询 - 内连接:相当于查询A、B交集的数据 - 外连接: - 左外连接:相当于查询A表所有数据和交集部分数据 - 右外连接:相当于查询B表所有数据和交集部分数据 - 子查询 */ -- 向表student_class 中添加数据 insert into student_class (id,address) values (1,'北京'); insert into student_class (id,address) values (2,'上海'); select * from student_class sc ; -- 向表student中添加数据 insert into student (id,name,age ,class) values ( 001, '李华',21,1); insert into student (id,name,age ,class) values ( 002, '小明',20,1); insert into student (id,name,age ,class) values ( 003, '小红',27,2); insert into student (id,name,age ,class) values ( 004, '小金',29,2); select * from student s ; select * from student , student_class where student.class = student_class.id ;
_多表查询,内连接&外连接
-
-- 隐式内连接 SELECT 字段列表 from 表1,表2... where 条件; -- 显示内连接 SELECT 字段列表 from 表1,
-
/* 1. 笛卡尔积:取A,B集合所有组合情况; 2. 多表查询::从多张表查询数据 - 连接查询 - 内连接:相当于查询A、B交集的数据 - 外连接: - 左外连接:相当于查询A表所有数据和交集部分数据 - 右外连接:相当于查询B表所有数据和交集部分数据 - 子查询 */ -- 向表student_class 中添加数据 insert into student_class (id,address) values (1,'北京'); insert into student_class (id,address) values (2,'上海'); select * from student_class sc ; -- 向表student中添加数据 insert into student (id,name,age ,class) values ( 001, '李华',21,1); insert into student (id,name,age ,class) values ( 002, '小明',20,1); insert into student (id,name,age ,class) values ( 003, '小红',27,2); insert into student (id,name,age ,class) values ( 004, '小金',29,2); select * from student s ; select * from student , student_class where student.class = student_class.id ;
_多表查询、子查询
-
子查询根据查询结果不同,作用不同;
-
单行单列:作为条件值,使用= != >< 等进行条件判断
-
select 字段列表 from 表 where 字段名 = (子查询);
-
多行单列:条件值,使用in等关键字进行条件判断
-
select 字段列表 from 表 where 字段名 in (子查询);
-
多行多列:作为虚拟表
-
select 字段列表 from (子查询) where 条件
-
-
/* 单行单列:作为条件值,使用= != >< 等进行条件判断 select 字段列表 from 表 where 字段名 = (子查询); */ -- 需求:查询居住再北京且年龄在21岁的学生名单 select id from student_class where address ='北京'; select * from student s where class = (select id from student_class where address ='北京') and age >=21; /* * 错误查询 select * from student ,student_class where (student.class= student_class.id) in (select id from student_class where address = '北京' ); select * from student ,student_class where student.class= student_class.id ; */
_事务的简介、四大特征
-
事务简介:
- 数据库的事务(Transaction)是一种机制、一个操作序列,包含了一组数据库操作指令
- 事务把所有的命令作为一个整体一起向系统提交或撤销操作请求,即这一组数据库命令要么同时成功,要么同时失败
- 事务是一个不可分割的工作逻辑单元
-
-- 开启事务 START TRANSACTION; 或者 BEGIN; -- 提交事务 COMMIT; -- 回滚事务 ROLLBACK;
-
事务的四大特征:
- 原子性(Atomicity):十五时不可分割的最小单位,要么同时成功,要么同时失败
- 一致性(Consistency):事务完成时,必须使所有的数据都保持一致状态
- 隔离性(Isolation):多个事物之间,操作的可见性
- 持久性(Durability):事务一旦提交或回滚,它对数据库中的数据的改就是永久的
-
MySQL事务默认自动提交
-
-- 查看事务的默认提交方式 SELECT @@autocommit; -- 1 自动提交 0 手动提交 -- 修改事务提交的方式 set @@autocommit = 0;
-