zoukankan      html  css  js  c++  java
  • 多表查询

    多表查询:联接查询、子查询、集合运算

    联接查询

    交叉联接:笛卡尔积

    select * from <表1>,<表2>

    内联接:有条件的联接

    select * from <表1> inner join <表2> on <条件> --SQL
    select * from <表1>,<表2> where <条件>          --T-SQL
    --条件一般为 A=B
    --不满足条件的两表里的数据全部删除

    外连接:保留 舍弃的记录

    select * from <表1> left/right join <表2> on <条件> where <条件>--SQL
    --where是对联接后的表进行条件筛选
    --left join保留左侧表1中没有联接上的数据
    --right join保留右侧表2中没有联接上的数据
    
    

    自连接:表与自身联接

    select * from <表1>[as] 别名, <表2>[as] 别名  where <条件>

     

     

    子查询(嵌套查询)

    不相关查询:子查询条件不依赖于主查询,先执行子查询再执行主查询

    select sname from s where sage=(
    select sage from s sname ='小明'
    )
    --查找s表中与小明同年龄的人的姓名
    --子查询可以独立存在,所以为不相关子查询
    
    select sname from s where sage in (
    select sage from s sname ='小明'
    )
    --多值时不能使用= 要用 in/not in

    相关子查询:子查询条件依赖于主查询

    select sname from s exists (
    select * from sc where cno='2' and s,sno=sc.sno
    )
    
    --相关循环的联接使用exists
    --查询选修了2号课程的学生的姓名
    --依次遍历外查询的表中的数据,将数据带入到内查询的表中,判断是否能找到满足内查询条件的记录
    --若能找到满足条件的记录,则返回为真,否则为假
    --no exists 表示不存在的为真

     

    select(子查询)

    from(子查询)

    where(子查询)

    集合查询

    并 R union S 

    select * fromwhere 条件 union select * fromwhere 条件 

    交 R intersect S

    select * fromwhere 条件 intersect select * fromwhere 条件 

    差 R except S

    select * fromwhere 条件 except select * fromwhere 条件 

    集合查询不是所有集合都可以使用

     

  • 相关阅读:
    058_从键盘读取一个论坛积分,判断论坛用户等级
    057_统计 Linux 进程相关数量信息
    bzoj3436
    bzoj1202
    bzoj1044
    bzoj2338
    bzoj1854
    bzoj1856
    830C
    bzoj2132
  • 原文地址:https://www.cnblogs.com/yrxc/p/12950367.html
Copyright © 2011-2022 走看看