zoukankan      html  css  js  c++  java
  • 连接查询

    连接查询

     

    先看个问题

    • 问:查询每个学生每个科目的分数
    • 分析:学生姓名来源于students表,科目名称来源于subjects,分数来源于scores表,怎么将3个表放到一起查询,并将结果显示在同一个结果集中呢?
    • 答:当查询结果来源于多张表时,需要使用连接查询
    • 关键:找到表间的关系,当前的关系是

        students表的id---scores表的stuid
        subjects表的id---scores表的subid

    • 则上面问题的答案是:
    select students.sname,subjects.stitle,scores.score
    from scores
    inner join students on scores.stuid=students.id
    inner join subjects on scores.subid=subjects.id;
    • 结论:当需要对有关系的多张表进行查询时,需要使用连接join

    连接查询

    • 连接查询分类如下:

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

    • 在查询或条件中推荐使用“表名.列名”的语法
    • 如果多个表中列名不重复可以省略“表名.”部分
    • 如果表的名称太长,可以在表名后面使用' as 简写名'或' 简写名',为表起个临时的简写名称

    练习

    • 查询学生的姓名、平均分
    select students.sname,avg(scores.score)
    from scores
    inner join students on scores.stuid=students.id
    group by students.sname;
    • 查询男生的姓名、总分
    select students.sname,avg(scores.score)
    from scores
    inner join students on scores.stuid=students.id
    where students.gender=1
    group by students.sname;
    • 查询科目的名称、平均分
    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;
  • 相关阅读:
    ps cc 2018安装
    eclipse 快速添加 set , get 方法
    电脑设置以太网
    C# 获取web.config配置文件内容
    C# @Page指令中的AutoEventWireup,CodeBehind,Inherits
    未能正确加载“Microsoft.VisualStudio.Implementation.EditorPackage”包
    C# 实现MD5加密
    mutex 简单介绍
    select @@IDENTITY
    C# vs2012创建报表
  • 原文地址:https://www.cnblogs.com/wwthuanyu/p/10069578.html
Copyright © 2011-2022 走看看