MySQL子查询相关使用

子查询的实质:一个 select 语句的查询结果能够作为另一个语句的输入值。子查询不仅可用于 where 子句中,还能够用于 from 子句中,此时子查询的结果将作为一个临时表(temporary table)来使用。

 

一、      单行子查询

 

1、 查询“战争”类题材电影的具体信息,要求输出片名和导演名。

select movieName 片名,director 导演名
from movie m,movie_type mtwhere typeID =(select id from movie_type where typeName='战争')

输出结果:

片名导演名
集结号冯小刚
投名状陈可辛
红海行动林超贤
智取威虎山徐克
集结号冯小刚
投名状陈可辛

2、 查询票价高于平均票价的电影信息,要求输出电影名和导演名

select movieName 片名,director 导演名
from movie
where ticketPrice>(select avg(ticketPrice) from movie)

输出结果:

片名导演名
让子弹飞姜文
集结号冯小刚
花样年华王家卫
无间道刘伟强
智取威虎山徐克
归来张艺谋

3、查询票价高于“战争”类题材的平均票价电影信息,要求输出电影名和导演名

select movieName 电影名,director 导演名
from movie
where ticketPrice>
(select avg(ticketPrice) from movie where typeId=
(select id from movie_type where typeName='战争'))

输出结果:

电影名导演名
让子弹飞姜文
集结号冯小刚
花样年华王家卫
无间道刘伟强
智取威虎山徐克
归来张艺谋

二、子查询和in、all 、any、some运算符

 

in比较符

1、 查询“战争”和“喜剧”类题材电影的相关信息,要求输出片名和导演名。

select movieName 片名,director 导演名
from movie m,movie_type mt
where typeID in(select id from movie_type where typeName in('战争','喜剧'))

输出结果:

片名导演名
集结号冯小刚
投名状陈可辛
红海行动林超贤
智取威虎山徐克
大内密探零零发向华强
心花路放宁浩

2、 查询客户“zhang01”顾客所预订电影的具体信息,要求输出电影名、导演名、票价和片长,并按照票价升序排列

select movieName 电影名, director 导演名,ticketPrice 票价,filmLength 片长
from movie
where ID in(select movieID from schedule where Id in
(select scheduleID from ticket_sell where customerid in
(select id from customer where username='zhang01')))
order by ticketPrice

输出结果:

电影名导演名票价片长
纵横四海吴宇森70108
无问西东李芳芳80138
心花路放宁浩90118

3、 使用连接查询实现上题。

all 运算符的含义如下:

当 <all 时,表示小于最小值。

当 >all 时,表示大于最大值

select distinct movieName 电影名,director 导演名,ticketPrice 票价,filmLength 片长
from movie m,schedule s,ticket_sell ts,customer c
where m.id=s.movieId and s.id=ts.scheduleId and ts.customerId=c.id and c.username ='zhang01'
order by ticketPrice

输出结果:

电影名导演名票价片长
纵横四海吴宇森70108
无问西东李芳芳80138
心花路放宁浩90118

 

4、查询比所有“喜剧”类题材电影的票价都高的电影信息,要求输出片名和导演名。

 

SQL文件:https://files.cnblogs.com/files/blogs/719245/movie.zip?t=1694069371&download=true

作者:编程小白-新成原文地址:https://www.cnblogs.com/xincheng24/p/17684782.html

%s 个评论

要回复文章请先登录注册