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;

         查看输出结果:

         

          

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

  • 相关阅读:
    vagrantfile 示例
    服务器raid查看
    redis 使用记录
    golang 典型并发任务
    percona-server-mongodb 通用二进制下载
    命令之iperf-服务器之间网络测速
    用awk在命令行处理分析日志
    python是解释型还是编译型
    使用github action发布python包到Pypi
    算法图解学习系列--第6章--广度优先搜索算法BFS
  • 原文地址:https://www.cnblogs.com/dreamyu/p/6931316.html
Copyright © 2011-2022 走看看