子查询
1 IN查询
select sname from student where dept in ( select dept from depts where name = ‘ zhangsan’ )
2 带有比较运算符子查询
查询与zhangsan一个系的所有同学的名字 select sname from student where dept = ( select dept from depts where name = ‘ zhangsan’ )
in 比对集合,=比对单个数据;
3 带有ANY或ALL谓词子查询
<any 小于子查询中最大值
>any 大于子查询中最小值
查询一班学生年龄大于二班所有人年龄的人 select name from ban_1 where age>ALL ( select age from ban_2 )
联合查询
联合两个表,以on为条件进行查询
内外之分仅是,外对内而言,无非多能完整显示一张表的数据;
内连接(返回交集)
select * from table_a inner join table_b on table_a.a_id = table_b.b_id;
左连接
左表(a_table)全显,而右表(b_table)只显 示符合搜索条件的记录。
右表记录不符合的地方均为NULL。
select * from table_a left join table_b on table_a.a_id = table_b.b_id;
on限制条件后,还可通过and ,or等添加外限条件;
select * from student join sc on student.sno=sc.sno and sc.sale >100;
组合查询
UNION查询注意事项:
1. UNION关键字只能连接查询语句
2. UNION关键字两侧的查询语句,结果集必须有相同的列数
3.union 组合查询,不会显示重复的数据,使用union all则显示完整;
经典查询
查询“c001”课程比“c002”课程成绩高的所有学生的学号;
select a.* from (select * from sc where sc.cno='c001') a , (select * from sc where sc.cno='c002') b where a.sno=b.sno and a.score>b.score;
a.*:表示显示a表全部内容原先为*;
(select * from sc where sc.cno='c001') a,用a代替全部,后一部分用逗号隔开;
where a.sno=b.sno and a.score>b.score; 此时ab已经独立,所以进行独立判断.
多重跨表查询:
select cname,score from sc,course,student where sc.sno=student.sno and course.cno=sc.cno and student.sname='李四';