zoukankan      html  css  js  c++  java
  • mysql带条件查询,联表查询

     

    ---恢复内容开始---

    1,用于设定所select出来的数据是否允许出现重复行(完全相同的数据行)

    all:允许出现——默认不写就是All(允许的)。

    distinct:不允许出现——就是所谓的“消除重复行”

    2,where:条件

    3,group by:分组依据 后面加表的字段名,通常只进行一个字段的分组

    mysql表查询语法形式:select [all | distinct] 字段名或表达式 from 表名 [where] [group by] [having] [order by] [limit];

    练习题:共有下面四张表    学生表:student  教师表:teacher  课程表:course 成绩表:score

    1,查询Score表中至少有5名学生选修的并以3开头的课程的平均分数

    --操作表score,以cno分组并且cno是以3开头,取出各个cno的总数,及与cno对应的degree的平均值

    select count(cno),avg(degree) from score where cno like '3%' group by cno;

    --从虚拟表中找到cno总数大于5的

    select * from

    (select count(cno) a,avg(degree) b from score where cno like '3%' group by cno) c

    where a>5;

    2,查询所有学生的Sno、Cname和Degree列

    --找到student的sno
     select sno from student;


     --找到score 的sno,degree,cno
     select sno,degree,cno from score;


     --找到course的cno
     select cno,cname from course;


     --组成新表cno sno degree
     select a.cno,b.sno,b.sname,a.degree from (select sno,degree,cno from score) a  join (select sno,sname from student) b on a.sno=b.sno;


     --组成有cname cno sn degree sname的表
     select d.cname,e.cno,e.sno,e.degree,e.sname
     from
       (select a.cno,b.sno,b.sname,a.degree from (select sno,degree,cno from score) a  join (select sno,sname from student) b on a.sno=b.sno) as e 
      join 
      (select cname,cno from course) as d
      on d.cno=e.cno;

    3,查询“95033”班学生的平均分

    --从student取sno class,条件是class是95033的

    select sno,class from student where class='95033';

    --取出score中sno degree

    select sno,degree from score;

    --将上面两张表组成一张,取degree的平均值

    select avg(degree) from

    (select sno,class from student where class='95033') a

    join

    (select sno,degree from score) b

    on a.sno=b.sno;

    4,查询选修“3-105”课程的成绩高于“109”号同学成绩的所有同学的记录

    --将109号的成绩取出

    select degree from score where sno='109' and cno='3-105';

    -- 得出最终表

    select * from score

    where

    degree>(select degree from score where sno='109' and cno='3-105')

    and cno='3-105';

    5,查询和学号为108的同学同年出生的所有学生的Sno、Sname和Sbirthday列

    --找到student中sno为108 的Sbirthday
    select year(sbirthday) from student where sno='108';


    -- 得出最终表
    select sno,sname,sbirthday from student

    where

    year(sbirthday)=(select year(sbirthday) from student where sno='108');

  • 相关阅读:
    初识sed和gwak
    USB驱动程序设计
    linux-usb软件系统架构
    CSS基础 布局
    CSS基础 样式属性
    CSS基础 样式分类、选择器
    HTML基础 页面效果(标题图标、锚点、插入音乐,视频、滚动效果、嵌入网页)
    HTML基础 常用标记
    HTML基础 表单
    HTML基础 初识 HTML(整体结构 文字 图片 表格 超链接)
  • 原文地址:https://www.cnblogs.com/sword082419/p/8947854.html
Copyright © 2011-2022 走看看