MySQL多表查询之GroupBy

来源:互联网 发布:excel用按钮录入数据 编辑:程序博客网 时间:2024/06/03 19:36

    需求:根据主键id查询到该顾客最近的一次消费记录



   SQL代码如下:

               SELECTcbi.id,cbi.mob,cbi.identity_card,bcil.remark,bcil.orders_no,bcil.brand_no,bcil.with_date,bcil.scoreFROMcustomer_base_info cbiLEFT JOIN(SELECTA.customer_id,A.with_date,A.remark,A.orders_no,A.brand_no,A.scoreFROMbrand_customer_integral_log A,(SELECTcustomer_id,MAX(with_date)max_with_dateFROMbrand_customer_integral_logGROUP BYcustomer_id)BWHEREA.customer_id = B.customer_idAND A.with_date = B.max_with_date) bcil ON (bcil.customer_id = cbi.id)WHEREcbi.id = '2c914df34997e204014997e2fe4e0001'
  

  用到的两张表:customer_base_info表为顾客基本信息,brand_customer_integral_log顾客消费记录表。


  一个顾客对应多个消费记录, 即一对N的。所以用customer_base_info去左连接。我第一反映也是和很多人一样直接左连接brand_customer_integral_log然后取ORDER BY(消费时间),最后根据customer_id来GROUP BY。 但结果是不对的。


  这是因为MySQL:

      写的顺序:select ... from... where.... group by... having... order by..
      执行顺序:from... where...group by... having.... select ... order by...

  在ORDER By之前结果就已经SELECT出来了, 所以这样的思路得到的结果是错误的。


  选用子查询来解决这个问题:

                       SELECTA.customer_id,A.with_date,A.remark,A.orders_no,A.brand_no,A.scoreFROMbrand_customer_integral_log A,(SELECTcustomer_id,MAX(with_date)max_with_dateFROMbrand_customer_integral_logGROUP BYcustomer_id)BWHEREA.customer_id = B.customer_idAND A.with_date = B.max_with_date

  把brand_customer_integral_log内连接, 根据customer_id查询出MAX(with_date)最近消费时间, 这样得到的才是所要的该顾客最近消费记录。

  

  结果如下:

  

  

2 0
原创粉丝点击