需求:根据主键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)最近消费时间, 这样得到的才是所要的该顾客最近消费记录。
结果如下: