where型子查询:
查出每个栏目最新的商品(以good_id为最大为最新商品):
goods货物表,good_id表的主键,cat_id栏目的编号
select cat_id,good_id,good_name from goods where good_id in(selct max(good_id) from goods group by cat_id);
form型子查询:
查出每个栏目最新的商品(以good_id为最大为最新商品):
select * from (select cat_id,good_id,good_name from goods order by cat_id asc, good_id desc) as tep group by cat_id;
from和where型综合练习:
查出挂科2门及以上同学的平均分:
思路讲解:
-- 1.先求出挂科两门以上及两门的同学
-- select name,count(*) as gk from stu where score<60 group by name having gk>=2;
-- 2.去除多余的一行
-- select name from (select name,count(*) as gk from stu where score<60 group by name having gk>=2)as tmp;
--3.最终结果
select name ,avg(score) as '平均分' from stu where name in(select name from (select name,count(*) as gk from stu where score<60 group by name having gk>=2)as tmp)
group by name;
查询结果:
其余5种:
department表:
employee表:
in子查询:查询年龄为20岁的员工部门
select * from department where did in(SELECT did from employee where age=20);
exists子查询:查询是否存在年龄大于21岁的员工
select * from department where EXISTS (SELECT did from employee where age>21);
any子查询:查询满足条件的部门
select * from department where did> any (SELECT did from employee );
all子查询:查询满足条件的部门
select * from department where did> all(SELECT did from employee );
比较运算符子查询:查询赵四是哪个部门的
select * from department where did= all(SELECT did from employee where name='赵四');
总结:
where型子查询:指把内部查询的结果作为外层查询的比较条件。
from型子查询:把内层的查询结果当成临时表,供外层sql再次查询。
in子查询:内层查询语句仅返回一个数据列,这个数据列的值将供外层查询语句进行比较。
exists子查询:把外层的查询结果,拿到内层,看内层是否成立,简单来说后面的返回true,外层(也就是前面的语句)才会执行,否则不执行。
any子查询:只要满足内层子查询中的任意一个比较条件,就返回一个结果作为外层查询条件。
all子查询:内层子查询返回的结果需同时满足所有内层查询条件。
比较运算符子查询:子查询中可以使用的比较运算符如 “>” “<” “= ” “!=”
今天的文章子查询包括哪几种_5种常用关系型数据库分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/77666.html