mysql关联查询和联合查询

一、内联方式

   1.传统关联查询

     "select * from students,transcript where students.sid=transcript.sid and transcript.total>600 and transcript.date=2015-6";

     上面是查询出在2015-6月,月考中总成绩超过600的学生信息。where的条件有三个,要看出是哪些是关联条件,哪些是查询过滤还是挺简单,若是多个表多个查询条件那么就不是那么容易了

   2.JOIN...ON

      "select * from students JOIN transcript ON(students.sid=transcript.sid) where transcript.total>600 and transcript.date=2015-6";

     这样能很容易看出ON后面括号即关联条件,where之后为过滤条件一目了然。语法中ON后的()不是必须的,但是为了代码风格建议添加。

 3.JOIN...USING

   "select * from students JOIN transcript USING(sid) where transcript.total>600 and transcript.date=2015-6";

    这个时候括号就是必须的了。这种写法很好,输入更少的单词,查询性能上没有太大的差异,但是JOIN...ON和传统关联查询查询时sid会出现二次。

 4.LEFT OUTER JOIN...ON

  "select * from students LEFT OUTER JOIN transcript USING(sid) where transcript.date=2015-6";

  选择表students所有数据,并将transcript的数据加到students表中,若transcript中不符合条件,就不用加入结果表中,并且NULL表示

 5.RIGHT OUTER JOIN...ON

  "select * from students RIGHT OUTER JOIN transcript USING(sid) where transcript.date=2015-6";

  选择表transcript所有数据,并将students的数据加到students表中,若students中不符合条件,就不用加入结果表中,并且NULL表示

 6.FULL OUTER JOIN...ON

  "select * from students FULL OUTER JOIN transcript USING(sid) where transcript.date=2015-6";

  选择表student、transcript所有数据,若students,students中不符合条件,就不用加入结果表中,并且NULL表示

posted on 2015-11-23 11:28  会学习的猪  阅读(6772)  评论(0编辑  收藏  举报

导航