如何从SQL JOIN中对结果进行排序? (Groupwise max?)

时间:2013-10-23 10:41:41

标签: mysql sql

我在查询时遇到了一些问题。我想要做的是选择有关我的用户的具体信息,还包括他们最新广告系列的最新日期和最新发票。

我目前正在返回结果,但发票和广告系列数据未按日期排序。

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是每个表的最新版本的情况下返回结果。?

0 个答案:

没有答案