• MySQL子查询


    ****************************子查询*********************************
    where型子查询:指把内层查询的结果作为外层查询的条件
    from型子查询:把内层的查询给过当成临时表,共外曾sql再次查询
    exists子查询:把外层查询的结果拿到内层,看内层的查询是否成立。
    #查有商品的栏目
    select cat_id,cat_name from category where exists(select * from goods where goods.cat_id=category.cat_id);
    **********************************************************
    where表达式
    表达式在哪一行成立,哪一行就取出来
    =,!=/<>,>,<,>=,<=
    in,between and
    or,and,not
    having
    分组,一般和统计函数配合使用
    max,min,avg,sum,count
    数据在表中,表在硬盘或内存以文件形式存在
    where就是针对表文件发挥作用的
    查询出的结果,也可以看成一张表,其文件一般临时存在缓冲区
    having就是针对查询的结果发挥作用
    order by表达式
    作用:排序
    可以针对字段,升序(asc),降序[desc]排列
    有可能一个字段也排不出的结果,可以选用其他字段继续排序
    order by 字段1[asc/desc],字段2[asc/desc]... ...
    limit限制条目
    limit [offset,N]
    offset:偏移量
    N:取出条目
    以取第3名-第5名:limit 2,3
    ************************************************************
    where子查询
    内层查询的结果作为外层查询的比较条件
    例:查最新商品(以goods_id最大为最新)
    select * from goods where goods_id=最大的goods_id
    select * from goods where goods_id=(select max(goods_id) from goods);
    from子查询
    把内层的查询结果供外层再次查询
    注意,内层的查询结果看成临时表,加'as'临时表名
    exists型子查询
    把外层的查询结果带入到内层,看内层是否成立
    查询有商品栏目
    select * from category where exists(select * from goods where goods.cat_id=category.cat_id);

    **********************where型子查询***********************
    #where型子查询:把内层查询的结果当做外层查询的一个条件。
    select goods_id,goods_name from goods_id=(select max(goods_id) from goods);
    #用where型子查询,查出每个栏目下最新的商品(以id最大为最新)。
    select cat_id,max(goods_id) from goods group by cat_id;
    select goods_id,cat_id,goods_name from goods where goods_id in(select max(goods_id) from goods group by cat_id);
    **************************from型的子查询**************************
    select goods_id,cat_id,goods_name from goods order by cat_id asc,id desc;
    select max(goods_id),cat_id from goods group by cat_id;
    select goods_is,cat_id,goods_name from goods where goods_id in(select max(goods_id),cat_id from goods group by cat_id;);
    #用from型的子查询查询出每个栏目的最新的商品
    select * from (select goods_id,cat_id,goods_name from order by cat_id asc,goods_id desc) as temp group by cat_id;
    select * from stu;
    #先把挂科两门及以上的同学找出来
    select name,count(*) from stu where score<60 group by name;
    select name,count(*) as gk from stu where score<60 group by having gk>=2;
    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 temp) group by name;


     

  • 相关阅读:
    iOS 开发学习之 User Interface(2)UIWindow 视窗
    iOS 开发学习之 User Interface(1)APP 生命周期
    OC-学习Tips
    初识Objective-C
    Android代码报错:setContentView(R.layout.activity_main)
    解决Discuz! info: MySQL Query Error
    技术网站
    java调用机器上的shell脚本
    素材网、图片库
    database工具
  • 原文地址:https://www.cnblogs.com/wyh3721/p/2557007.html
Copyright © 2020-2023  润新知