mysql多列 groupby,MySQL多表查询之GroupBy

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

SQL代码如下:

SELECT

cbi.id,

cbi.mob,

cbi.identity_card,

bcil.remark,

bcil.orders_no,

bcil.brand_no,

bcil.with_date,

bcil.score

FROM

customer_base_info cbi

LEFT JOIN(

SELECT

A.customer_id,

A.with_date,

A.remark,

A.orders_no,

A.brand_no,

A.score

FROM

brand_customer_integral_log A,

(

SELECT

customer_id,

MAX(with_date)max_with_date

FROM

brand_customer_integral_log

GROUP BY

customer_id

)B

WHERE

A.customer_id = B.customer_id

AND A.with_date = B.max_with_date

) bcil ON (bcil.customer_id = cbi.id)

WHERE

cbi.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出来了, 所以这样的思路得到的结果是错误的。

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

SELECT

A.customer_id,

A.with_date,

A.remark,

A.orders_no,

A.brand_no,

A.score

FROM

brand_customer_integral_log A,

(

SELECT

customer_id,

MAX(with_date)max_with_date

FROM

brand_customer_integral_log

GROUP BY

customer_id

)B

WHERE

A.customer_id = B.customer_id

AND A.with_date = B.max_with_date

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

结果如下:

850ca76f2f143d251bf76928d9b42159.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值