大家好,欢迎来到IT知识分享网。
外键有三种约束模式:
- district : 严格模式(默认的),父表不能删除或更新一个已经被子表数据引用的记录。
- cascade : 级联模式,父表的操作,对应子表关联的数据也跟着操作。
- set null : 置空模式,父表被操作之后,子表对应的外键字段被置空。
- 通常情况下,合理的模式应该是这样的:删除父表中的数据,子表置空,更新父表的时候,子表做级联操作。
-
-- 指定模式的语法:foreign key(外键字段) references 父表(外键字段) on delete 模式 on update 模式foreign key(外键字段) references 父表(外键字段) on delete set null on update cascade-- 创建外键,指定模式:删除置空,更新级联create table my_foreignthree(id int primary key auto_increment,name varchar(20) not null,c_id int,-- 增加外键foreign key(c_id)-- 引用表references my_class(c_id)-- 指定删除模式on delete set null-- 指定更新模式on update cascade)charset utf8;
-
联合查询:将多次查询(多条select语句),在记录上进行拼接。
联合查询
-- 基本语法多条select构成,每一条select语句获取的字段数必须严格一致(与字段类型无关)。select 语句1union [union 选项]select 语句2...union选项:all: 保留所有distinct: 去重:默认的-- 联合查询select c_id,c_name,c_room from my_classunion -- 去重select studentid,number,name from my_student;-- 联合查询select c_id,c_name,c_room from my_classunion all -- 不去重select studentid,number,name from my_student;
联合查询的意义
联合查询意义:
- 查询同一张表,但是需求不同:如查询学生信息,男生身高升序,女生身高降序
- 多表查询:多张表的结构是一样的,保存的数据的结构也是相同的。
联合查询中:order by不能直接使用,需要对查询语句使用括号才行。
-- 需求:男生升序,女生降序(年龄)(select * from my_student where gender='boy' order by age asc)union(select * from my_student where gender='girl' order by age desc);
可以发现,虽然使用了order by关键字,但是并没有达到预期效果,此时需要注意的是,若要order by生效,必须搭配limit,limit使用限定的最大数。
-- 需求:男生升序,女生降序(年龄)(select * from my_student where gender='boy' order by age asc limit 500)union(select * from my_student where gender='girl' order by age desc limit 500);
子查询
子查询:查询是在某一个查询结果集中查询
子查询分类
子查询有两种分类方式:按位置,按结果
- 按位置:子查询(select语句)在外部查询(select 语句)中出现的位置。
from 子查询
where 子查询
exists 子查询 - 按结果分类: 根据子查询得到的结果进行分类
标量子查询: 子查询得到的结果是一行一列
列子查询: 子查询得到的额结果是一列多行
行子查询: 子查询得到的结果是多行多列
表子查询: 子查询得到的结果是多行多列
-- 获取java003班的所有学生select * from my_student where c_id=?select c_id from my_class where c_name='java003'-- 标量子查询select * from my_student where c_id= (select c_id from my_class where c_name='java003')
-- 查询有效班级里的学生信息-- 确定数据源select * from my_student where c_id in(?)-- 确定有效班级select c_id from my_class-- 列子查询select * from my_student where c_id in (select c_id from my_class);
-- 查询学生中年龄最大且身高最高的学生-- 行子查询select * from my_student where (age,height) = (select max(age),max(height) from my_student);
-- 找出每个班中最高的学生-- 表子查询select * from (select * from my_student order by height desc) as student group by c_id;
exists子查询:用来判断某些条件是否满足(跨表),exists是接在where之后,exists返回的结果:0或者1
-- 查询有所属班级的所有学生信息select * from my_student where exists(select * from my_class)
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/116931.html






