1

我对这个查询有一些问题。我要做的是选择有关我的用户的特定信息,但还包括他们最新活动的最新日期和最新发票。

我目前正在返回结果,但发票和活动数据未按日期排序。

SELECT cu.uid, cu.email, cu.company, cu.phone, cu.first_name, cu.last_name, cu.city, cu.crdate,     sc.crdate, invoice.total
FROM  `corp_users` cu
LEFT JOIN sponsored_campaigns AS sc ON cu.uid=sc.userid 
LEFT JOIN corp_invoices AS invoice ON cu.uid=invoice.userid
WHERE cu.company != ""
GROUP BY cu.uid
ORDER BY cu.crdate DESC

我已经阅读了有关 groupwise-max 的资源(http://jan.kneschke.de/projects/mysql/groupwise-max/),但我无法让它正常工作。按照代码的步骤执行后,看起来像这样,并且在返回行中,它始终在用户日期上显示 NULL。

SELECT cu.uid, cu.email, cu.company, cu.phone, cu.first_name, cu.last_name, cu.city, cu.crdate, sc.crdate, invoice.total
FROM  `corp_users` cu

LEFT JOIN (
SELECT a.uid, MAX(b.crdate) MaxInvoice, MAX(c.crdate) MaxCampaign FROM corp_users a 
LEFT JOIN corp_invoices b ON a.uid=b.userid 
LEFT JOIN sponsored_campaigns c ON a.uid=b.userid 
GROUP BY a.uid
) temp ON cu.uid=temp.uid

LEFT JOIN sponsored_campaigns AS sc ON cu.uid=sc.userid AND sc.crdate=temp.MaxCampaign
LEFT JOIN corp_invoices AS invoice ON cu.uid=invoice.userid AND invoice.crdate=temp.MaxInvoice
WHERE cu.company != ""
GROUP BY cu.uid
ORDER BY cu.crdate DESC

总结我的问题。如何返回 sc.crdate 和 invoice.crdate 是每个表中最新的结果。?

4

0 回答 0