zoukankan      html  css  js  c++  java
  • MySQL(8):连接、子查询

        1.连接查询分类

        (1)表A inner join 表B:

        表A与表B匹配的行会出现在结果中。

        (2)表A left join 表B:

        表A与表B匹配的行会出现在结果中,外加表A中独有的数据,未对应的数据使用null填充。

        (3)表A right join 表B:

        表A与表B匹配的行会出现在结果中,外加表B中独有的数据,未对应的数据使用null填充。

    注意:即使没有外键约束,两表之间也能进行连接查询!!!!!


        2.连接查询注意事项

        (1) 在查询或条件中推荐使用“表名.列名”的语法。

        (2)如果多个表中列名不重复可以省略“表名.”部分。

        (3)如果表的名称太长,可以在表名后面使用' as 简写名'或' 简写名',为表起个临时的简写名称。


        3.实例:查询每个学生每个科目的分数

        分析:学生姓名来源于students表,科目名称来源于subjects,分数来源于scores表,怎么将3个表放到一起查询,并将结果显示在同一个结果集中呢?

        答:当查询结果来源于多张表时,需要使用连接查询。关键在于找到表间的关系,当前的关系是students表的id---scores表的stuid,subjects表的id---scores表的subid。

        则上面问题的答案是:

    select students.sname,subjects.stitle,scores.score
    from scores    //此处将scores改为students或subjects皆可,当然这会影响到inner join处的语句
    inner join students on scores.stuid=students.id    //inner join 后的表必须与on后的语句相关,且不可与from语句后的表相同
    inner join subjects on scores.subid=subjects.id;

        结论:当需要对有关系的多张表进行查询时,需要使用连接join。


        4.代码演示

    查询学生的姓名、平均分
    select students.sname,avg(scores.score)
    from scores
    inner join students on scores.stuid=students.id
    group by students.sname;    
    //最后一句可改为group by stuid,这样改可以避免学生姓名重名带来的错误
    //stuid其实可以不用加上scores的前缀,因为该字段只在scores中存在
    //stuid进行分组时,由于一个id能确定只对应一个学生name,因此学生name可以被获取显示;但由于一个学生id对应多行scores表数据,因此这多行数据只能被获取,无法被直接显示
    
    查询男生的姓名、总分
    select students.sname,avg(scores.score)
    from scores
    inner join students on scores.stuid=students.id
    where students.gender=1
    group by students.sname;    //此处说明group后的语句部分不用与from后的表名相关
    
    查询科目的名称、平均分
    select subjects.stitle,avg(scores.score)
    from scores
    inner join subjects on scores.subid=subjects.id
    group by subjects.stitle;
    
    查询未删除科目的名称、最高分、平均分
    select subjects.stitle,avg(scores.score),max(scores.score)
    from scores
    inner join subjects on scores.subid=subjects.id
    where subjects.isdelete=0
    group by subjects.stitle;


        6.子查询

        子查询支持嵌套使用

    查询未被删除的学号最小的学生的所有信息
    select * from students where id=(select min(id) from students where isDelete=0);
  • 相关阅读:
    SpringBoot优雅的全局异常处理
    react格式化展示json
    Pycharm调试按钮
    HttpURLConnection和okhttp的使用
    objection自动生成hook代码
    hookString
    python取中位数 位运算
    scrapy mongo pipeline
    xpath tips
    IT日语
  • 原文地址:https://www.cnblogs.com/wangchongzhangdan/p/9409608.html
Copyright © 2011-2022 走看看