mysql 高级查询

####1、嵌套子查询和相关子查询
子查询:
1、一个询语句中还包含其他查询。其中包含其他查询的查询叫父查询,被包含的查询叫子查询。
2、子查询也可以和UPDATE、INSERT、DELETE一起使用,语法类似于SELECT语句 。
3、子查询中可以再包含子查询,即允许多层嵌套。
select * from student where age>(select age from student where stuname=‘张宏’);
嵌套子查询:非相关子查询。
1、使用比较运算符的子查询
###注意:将子查询和比较运算符联合使用,必须保证子查询返回的值不能多于一个(单值)
select * from student where age>(select age from student where stuname=‘张宏’);
2、使用[not] in 子查询 范围子查询。当子查询返回多值时,使用这种方式
select * from student where student where stuid in (select stuid from grade where courseid=1);
3、any all 子查询
#查询其他系中比信息系任意一个学生入学成绩低的学生信息
select stuname,ingrade from student where class<>‘信息系’ and ingrade< any (select max(ingrade) from student where class=‘信息系’);
#查询其他系中比信息系所有学生数学成绩低的学生信息
select stuname,ingrade from student where class<>‘信息系’ and ingrade< all (select min(ingrade) from student where class=‘信息系’);
关联子查询:exists存在性查询

####2、通过在子查询中使用EXISTS子句,可以对子查询中的行是否存在进行检查
###使用关联字查询 EXISTS ,会对外层用loop逐条查询,每次查询都睡去查看对应的exists语句。
* 非关联子查询中子查询只会执行一次返回结果集
* 关联子查询存在性判断exists中子查询会重复执行,外层查询有多少条记录,内层子查询就要执行多少次,判断存在性。
select stuname from student where exists(select 1);
####3、多表联接查询
1、内联接

	select s.stuid, s.stuname,g.courseid,g.grade,c.coursename
	from student s,grade g,course c 
	where s.stuid = g.stuid and c.courseid=g.courseid and g.grade>=90 
	order by g.grade,g.courseid limit 5,5;

2、外联接

	select s.stuid, s.stuname,g.courseid,g.grade
	from student s left join grade g
	on s.stuid = g.stuid where g.grade>90;

3、自联接

	select e1.empno,e1.mgr,e2.ename from emp e1, emp e2
	where e1.mgr = e2.empno;

4、交叉联接:笛卡尔积

	select * from student,grade;

5、使用表的别名

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值