zoukankan      html  css  js  c++  java
  • 2.SQL语言进阶

    0.实验数据

     

    表1.course表

    表2.student表

    表3.sc表

    1.SQL连接

    • 内连接
        • select * from student,sc where student.sno=sc.sno;//相等连接,也可以用!=,<=等来连接
        • select * from student inner join sc using(sno);
        • select * from student inner join sc on student.sno=sc.sno;  
    • 外连接
        • 左外连接: select * from student left join using(sno);
        • 右外连接: select * from student right join using(sno);
        • 全连接:mysql 貌似不支持,不过可以使用union进行间接实现
    • 笛卡尔积
        • select * from student,sc; 
    • 自连接
        • student表自己连接自己
        • select * from student s1,student s2 where s1.sno=s2.sno;//为表创建了两个别名    

    2.子查询

    • 子查询的分类
    • 1.嵌套子查询----先执行子查询把结果返回给,父查询
    • 2.相关联子查询--父查询把数据按照行一次传递给子查询,子查询判定是否满足子查询条件后,返回boolean值给父查询,父查询决定是否保留这条数据,直到所有的数据处理完毕。(比较难)
    • 嵌套子查询
    • 1.Books表,列:ClassID,bookName,publish,price
    • Q1:查询所有价格高于平均价格的图书名,出版社和价格
    • select bookName,publish,price from Books where price>(select avg(price) from books);
    • 2.sc表,列:sno(学号),cno(课程号),grade
    • Q1:查询只有一人选修的课程
    • select cno from sc group by cno having count(*)=1;
    • 相关联子查询
    • 1.sc表,列:sno(学号),cno(课程号),grade
    • Q1:查询只有一人选修的课程(相关子查询-理解为没有和别人选同一门的课程)
    • select cno from sc scx where cno not in (select cno from sc where sno!=scx.sno);
    • 2.sc表,列:sno(学号),cno(课程号),grade
    • Q2:查询每个科目的前两名

    • select * from sc where (select count(*) from sc scx where sc.cno=cno and grade>sc.grade)<2 order by cno,sno;  
    • In与Exists选择
    • 1.select * from A where id in (select id from B)
    • 当B表的数据集必须小于A表的数据集时,用in优于exists
    • 2.select * from A where exists (select 1 from B where B.id = A.id)
    • 当A表的数据集系小于B表的数据集时,用exists优于in。

    参考文献

    http://blog.csdn.net/ghyg525/article/details/28272007

  • 相关阅读:
    入门指引之永久素材
    入门指引之上传临时素材
    入门指引之查看accesstoken
    java中的左移 右移
    病狗问题
    leetcode 几何题 位运算 面试编程
    CNN网络参数
    python学习整理
    JAVA问题整理
    计算机网络整理
  • 原文地址:https://www.cnblogs.com/yangyunnb/p/6409256.html
Copyright © 2011-2022 走看看