zoukankan      html  css  js  c++  java
  • mysql学习笔记(七)—— MySQL内连接和外连接

        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;

         外连接包含左右连接,

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

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

         上面的那个语句的输出结果是这样的:

         

         为了做个比较,我在customers表中也做了一条数据,该数据并没有订单信息,我们使用左连接来看下:

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

         看下结果:

        

        这样应该就能很清晰看出内连接和外连接的作用了吧。

     MySQL使用带聚集函数的联结

         上面只是想知道哪些客户有订单,假如我们想看下每个客户都有多少订单呢?这就需要用到之前学过的聚集函数了

         select customers.cust_name,customers.cust_id,count(orders.order_num) as counts from customers inner join orders on customers.cust_id = orders.cust_id group by customers.cust_id;

         查看输出结果:

         

          

          以上就是一些高级联结的使用。

  • 相关阅读:
    关于Maya Viewport 2.0 API 开发的介绍视频
    春节大假
    Some tips about the life cycle of Maya thread pool
    Can I compile and run Dx11Shader for Maya 2015 on my side?
    How to get current deformed vertex positions in MoBu?
    想加入全球首届的 欧特克云加速计划吗?
    三本毕业(非科班),四次阿里巴巴面试,终拿 offer(大厂面经)
    mac、window版编辑器 webstorm 2016... 永久破解方法。
    node 搭载本地代理,处理web本地开发跨域问题
    js 一维数组,转成嵌套数组
  • 原文地址:https://www.cnblogs.com/dreamyu/p/6931316.html
Copyright © 2011-2022 走看看