前言
本章我们将学习SQL查询中的高级部分,如内连接、外连接和子查询,通过这些查询技术我们将能够解决项目中复杂的查询问题。
外键约束
MySQL属于关系型的数据库,表之间可以建立关系,如:学生表和成绩表,在成绩表中添加学生编号引用学生表中的学生编号,这样在成绩表中就不用添加重复的学生信息了,这种关系也叫主外键关系,可以通过设置外键约束实现。
可以在创建表时,添加外键约束来保证表和表之间引用完整性,添加外键后:
在插入外键表数据前,必须先插入主表数据
在删除主表数据前,必须先删除外键表数据
语法:
create table 表名
(
字段名类型约束,
... ,
constraint 外键名称 foreign key (外键列) references 主表(主键)
);
代码示例:
use mysql_db;-- 创建成绩表drop table if exists tb_score;create table tb_score( score_id int primary key auto_increment, score_stu_id int, score int, score_course varchar(20), constraint fk_score_stu_id foreign key(score_stu_id) referencestb_student(stu_id));
内连接查询
在查询时我们经常要把相关的多张表的字段,一起查询出来,如查询学生成绩时,要显示分数和学生姓名。这个时候我们就需要连接查询了,连接查询分为内连接和外连接,我们先学习内连接查询。
内连接查询的特点是:会查询出相关表中都存在的数据。
语法有两种实现方法:
1)select 字段..... from 表1 inner join 表2
on 表1.主键 = 表2.外键;
注意:这里假设表1是主表,内连接表的前后顺序无关
2)select 字段..... from 表1 , 表2
where 表1.主键 = 表2.外键;
代码示例:
-- 查询学生姓名和成绩方式1 select s.stu_id ,s.stu_name,c.score_course,c.score from tb_score c innerjoin tb_student s on s.stu_id = c.score_stu_id;-- 方式2 select s.stu_id ,s.stu_name,c.score_course,c.score from tb_score c ,tb_student s where s.stu_id = c.score_stu_id;
效果相同:
外连接查询
外连接分为左外连接和右外连接:
1) 左外连接
连接查询多张表的数据,显示所有左表的数据,右表存在不相符的数据补null。
语法:
select 字段... from 左表 left join 右表
on 主表.主键 = 子表.外键;
代码示例:
-- 左外连接,查询学生姓名和成绩selects.stu_id,s.stu_name,c.score_course,c.score from tb_student s left join tb_scorec on s.stu_id = c.score_stu_id;
-- 查询所有参加过考试的同学 selects.stu_id,s.stu_name,c.score_course,c.score from tb_student s left join tb_scorec on s.stu_id = c.score_stu_id where c.score is not null;
-- 查询所有没参加过考试的同学selects.stu_id,s.stu_name,c.score_course,c.score from tb_student s left join tb_scorec on s.stu_id = c.score_stu_id where c.score is null;
2)右外连接
与左连接相反,显示所有右表数据,左表中不相符的数据补null。
语法:
select 字段... from 左表 right join 右表
on 主表.主键 = 子表.外键;
代码示例:
selects.stu_id,s.stu_name,c.score_course,c.score from tb_score c right jointb_student son s.stu_id = c.score_stu_id;
总结
在SQL查询中,常用的查询是连接查询,连接查询又分为内连接和外连接查询。