这并不难。请查看我不久前回答的这篇文章,了解有关使用 JOIN 的一些背景信息。
在 MySQL 子查询中选择多个列/字段
这是您需要的技巧:查找每个客户 ID 的最新日期的子查询。这是:
SELECT customer_id, MAX(date) as date
FROM loyalty_codes_redeem_history
GROUP BY customer_id
然后你需要把这个子查询——这个虚拟表——加入到你的整体查询中。我认为结果将如下所示:
SELECT gv.amount AS gv_amount,
gv.customer_id AS gv_customer_id,
customer_latest_date.date AS h_date,
c.loyalty_id AS c_loyalty_id
FROM coupon_gv_customer gv
INNER JOIN loyalty_codes_redeem_history h
ON gv.customer_id = h.customer_id
INNER JOIN customers c
ON gv.customer_id = c.customers_id
INNER JOIN (
SELECT customer_id,
MAX(date) AS date
FROM loyalty_codes_redeem_history
GROUP BY customer_id
) customer_latest_date
ON customer_latest_date.customer_id = c.customers_id
你明白它是如何工作的吗?子查询在 INNER JOIN 中使用,就好像它是一个表,实际上它是:一个虚拟表。
编辑
要汇总您的 coupon_gv_customer 表中的忠诚度积分,您需要另一个汇总查询,如下所示:
SELECT customer_id,
SUM(amount) AS amount
FROM coupon_gv_customer
GROUP BY customer_id
然后,我认为您的查询将是这样的。它会给每个客户一排,我认为这是你想要得到的。没有任何兑换或日期的客户将不会出现。
SELECT c.customers_id,
c.loyalty_id,
customer_latest_date.date
customer_points.amount
FROM customers c
INNER JOIN (
SELECT customer_id,
SUM(amount) AS amount
FROM coupon_gv_customer
GROUP BY customer_id
) customer_points ON c.customers_id = customers_points.customer_id
INNER JOIN (
SELECT customer_id,
MAX(date) AS date
FROM loyalty_codes_redeem_history
GROUP BY customer_id
) customer_latest_date ON customer_latest_date.customer_id = c.customers_id