MySQL:联接2个表并显示子表的最后日期

时间:2019-04-01 17:41:04

标签: mysql sql join

我需要显示一个客户列表,其中包括他们的总购买数量和花费的总金额,此外,我还需要显示一列其最后购买日期的客户。

这是我当前的查询,但没有显示上次购买的最后可用日期:

SELECT user.id_user AS id,
purchase.date_insert AS last_purchase,
CONCAT(user.lastname, " ", user.name) AS name,
COUNT(purchase.id_purchase) AS purchases,
SUM(purchase.total) AS total
FROM user
JOIN purchase ON purchase.id_user = user.id_user
GROUP BY user.id_user
ORDER BY name

我需要获取该列的LAST可用值,而不是仅使用purchase.date_insert AS last_purchase(正在检索该列的第一个可用值)。

这是结构的sqlfiddle和一些数据示例:http://sqlfiddle.com/#!9/d83684/1

如示例所示,last_purchase列显示 2019-03-26T09:38:40Z ,它应为 2019-04-01 12 :01:24Z

谢谢!

2 个答案:

答案 0 :(得分:3)

我认为您必须要max()

SELECT u.id_user AS id,
       MAX(p.date_insert) AS last_purchase,
       CONCAT(u.lastname, ' ', user.name) AS name,
       COUNT(p.id_purchase) AS purchases,
       SUM(p.total) AS total
FROM user u JOIN
     purchase p
     ON p.id_user = u.id_user
GROUP BY u.id_user
ORDER BY MAX(u.name);

在大多数数据库中-包括具有默认设置的最新版本的MySQL-查询将返回错误。您在SELECTORDER BY中有一些列不是聚合键,也没有聚合。

答案 1 :(得分:0)

只使用max()

SELECT user.id_user AS id,
max(purchase.date_insert) AS last_purchase,
CONCAT(user.lastname, " ", user.name) AS name,
COUNT(purchase.id_purchase) AS purchases,
SUM(purchase.total) AS total
FROM user
JOIN purchase ON purchase.id_user = user.id_user
GROUP BY user.id_user,user.lastname,user.name
ORDER BY name

而且我更喜欢使用group by的非聚集列,如果不使用group by中的那些,mysql不会返回错误