oracle 两表关联查询


oracle 两表关联查询

CreationTime--2018年7月4日17点27分

Author:Marydon

情景描述

  查询学生表student,sname,sex,age信息及所在班级clazz表

1.使用左连接

select sname, sex, age, cname
  from student t1
  left join clazz t2
    on t1.cid = t2.cid;

2.使用(+),oracle独有

select sname, sex, age, cname
  from student t1, clazz t2
 where t1.cid = t2.cid(+);

3.from后面跟两张表

select sname, sex, age, cname
  from student t1, clazz t2
where t1.cid = t2.cid;

4.作为主表的查询字段

select sname,
       sex,
       age,
       (select cname from clazz t2 where t1.cid = t2.cid) cname
  from student t1;

小结

  前2种方式,是左连接的方式实现,学生表作为主表,当学生表中的班级cid在班级表中找不到时,班级名称cname填充内容为空;

  后2种方式,只查询出2表均能够匹配到的数据,学生表的数据不一定能查出所有记录。

拓展

  只有Oracle数据库可以使用(+)来代替左连接和右连接;

  "(+)"在"="右侧,表示的是:左连接,如:t1.cid = t2.cid(+);左表(学生表)为主表;

  "(+)"在"="左侧,表示的是:右连接,如:t1.cid(+) = t2.cid;右表(班级表)为主表。

 

 相关推荐:

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM