zoukankan      html  css  js  c++  java
  • 六、子查询

    Where型子查询:指把内层查询的结果作为外层查询的比较条件
    案例:查出每一个栏目下面最新的商品
    select goods_id,cat_id,goods_name from goods where goods_id in (select max(goods_id) from goods group by cat_id);
    From型子查询:把内层的查询结果当成临时表,供外层SQL再次查询
    案例:同上题
    select * from (select goods_id,cat_id,goods_name from goods order by cat_id asc,goods_id desc) as tmp group by cat_id;
    思考:如何用子查询查出挂科两门及以上同学的平均分,where型,from型都可以
     
    select name,avg(score) 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;
    上例,我们用where+from型子查询,得出挂科2门及以上同学的成绩。
    Exits子查询:
    把外层的查询结果代入到内层,看内层是否成立。如果内层成立,就把这个结果取出来,如果内层不成立,那就把这个结果丢弃。
    两张表:
    Categorygoods
    Category表里面的内容如下:
    Cat_id
    Cat_name
    1
    手机类型
    2
    CDMA手机
    3
    GSM手机
    4
    3G手机
    5
    双模手机
    6
    手机配件
    7
    充电器
    8
    耳机
    9
    电池
    案例:不把9个栏目全部取出来,只把栏目下面有商品的给取出来
    select cat_id,cat_name from category where exists (select * from goods where goods.cat_id=category.cat_id);
    我们假设category表下面的栏目cat_id的值为1,那我们把这个值代入到select * from goods where goods.cat_id=category.cat_id语句当中就变成了select * from goods where goods.cat_id=1;如果这个语句是空的,那么它就会丢弃,不是空的它就会取出来。
     
  • 相关阅读:
    编写有效用例_阅读笔记05
    编写有效用例_阅读笔记04
    编写有效用例_阅读笔记03
    编写有效用例_阅读笔记02
    软件需求与分析课堂讨论一
    编写有效用例_阅读笔记01
    问题账户需求分析
    【知识总结】动态 DP
    【知识总结】数论全家桶
    【知识总结】多项式全家桶(三点五)(拆系数解决任意模数多项式卷积)
  • 原文地址:https://www.cnblogs.com/steven9898/p/11339426.html
Copyright © 2011-2022 走看看