码迷,mamicode.com
首页 > 数据库 > 详细

MySQL内连接和外连接

时间:2018-09-20 21:21:34      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:sql   客户   out   条件   左右   订单   等值连接   信息   mys   

  • INNER JOIN(内连接,或等值连接):获取两个表中字段匹配关系的记录。
  • LEFT JOIN(左连接):获取左表所有记录,即使右表没有对应匹配的记录。
  • RIGHT JOIN(右连接): 与 LEFT JOIN 相反,用于获取右表所有记录,即使左表没有对应匹配的记录。

 

 

MySQL内连接(inner join on)

      MySQL的内连接使用inner join on,它的效果跟使用where是一样的,如果联结的是两个表,那么需要左右的条件或者说字段是需要完全匹配的。

      来看个例子:有两张表customers客户表和orders订单表,外键是cust_id,我们需要知道哪些客户有订单     

     select customers.cust_id,orders.order_num from customers , orders where customers.cust_id = orders.cust_id;

     如果我们使用内连接的话就可以这样写:

     select customers.cust_id,orders.order_num from customers inner join orders on customers.cust_id = orders.cust_id;

     但是如果我除了这些有有客户的订单,我还想拿到所有的订单信息,那么怎么办呢?

  MySQL外连接(left,right)

     select customers.cust_id,orders.order_num from customers right outer join orders on customers.cust_id = orders.cust_id;

     外连接包含左右连接,

     左连接的结果是除了匹配条件的数据还包含左边表中的所有数据

     右连接的结果是除了匹配条件的数据还包含右边表中的所有数据

MySQL内连接和外连接

标签:sql   客户   out   条件   左右   订单   等值连接   信息   mys   

原文地址:https://www.cnblogs.com/niuli1987/p/9683115.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!