zoukankan      html  css  js  c++  java
  • 分组查询与内外连接查询

    一. 分组查询


       1.语法

        SELECT ... FROM ... GROUP BY ...

        --分组查询Group by
        select COUNT(*) as 学生人数,GradeId as 年级编号 from Student group by GradeId

       2.进行多表之间的分组查询

        --查询每门课程的平均分
        --where 和 group by 和 order by 的顺序
        select AVG(StudentResult) as 平均分,SubjectName as 课程名称 from Subject,Result
        where Subject.SubjectId=Result.SubjectId group by Subject.SubjectName order by 平均分

       3.多列分组

        --查询每学期男女同学的总人数
        select COUNT(*) as 学生人数,GradeId as 年级编号,Sex as 性别 from Student group by GradeId,Sex

       4.使用having字句帮助group by进行分组条件筛选,注意:条件必须在聚合函数内或者查询的分组条件内


        --查询学生总人数超过5人的年级
        select COUNT(*) as 学生人数,GradeId as 年级编号 from Student group by GradeId having COUNT(*) >5


      二. 内连接 inner join on

       1.内连接可以不用区分表与表之间的顺序,但是要指定好关系
       2.内连接可以将inner省略
       3.通where语句效果相同

       select stu.StudentName,res.StudentResult,res.SubjectId from Student as stu inner join Result as res on (stu.StudentNo=res.StudentNo)

       4.在查询不同记录时,会将表与表中的记录数相乘然后减去相同的记录数

       select stu.StudentName,res.StudentResult,res.SubjectId from Result as res  inner join Student as stu on (stu.StudentNo<>res.StudentNo)

       例如:12*10-10

      三. 外连接

       1.左外连接 LEFT JOIN 左边的表作为主表

        select StudentName,StudentResult,Student.StudentNo from Student LEFT JOIN Result on Student.StudentNo=Result.StudentNo

       2.右外连接  RIGHT JOIN 右边的表作为主表

        select StudentName,StudentResult,Student.StudentNo from Student RIGHT JOIN Result on Student.StudentNo=Result.StudentNo

  • 相关阅读:
    poj 2187 Beauty Contest(旋转卡壳)
    poj 2540 Hotter Colder(极角计算半平面交)
    poj 1279 Art Gallery(利用极角计算半平面交)
    poj 3384 Feng Shui(半平面交的联机算法)
    poj 1151 Atlantis(矩形面积并)
    zoj 1659 Mobile Phone Coverage(矩形面积并)
    uva 10213 How Many Pieces of Land (欧拉公式计算多面体)
    uva 190 Circle Through Three Points(三点求外心)
    zoj 1280 Intersecting Lines(两直线交点)
    poj 1041 John's trip(欧拉回路)
  • 原文地址:https://www.cnblogs.com/yjc1605961523/p/9380575.html
Copyright © 2011-2022 走看看