选择最大值和相应列

时间:2014-08-04 11:01:04

标签: php mysql sql

我试图从更新列中获取最大日期,但也从该表返回相应的全名,目前正在发生的是返回最新的updates.date,但是第一个updates.consultant当前正在返回好吧,我们需要MAX日期的正确全名。

SELECT customer.id, 
       customer.name, 
       customer.retainer_value, 
       customer.customer_type, 
       clientdetails.performance, 
       clientdetails.url, 
       members.fullname AS acc_manager, 
       u.maxdate, 
       u.fullname 
FROM   customer 
       LEFT JOIN clientdetails 
              ON clientdetails.id = customer.id 
       LEFT JOIN members 
              ON members.id = customer.consultant_name 
       LEFT JOIN (SELECT updates.clientid, 
                         members.fullname, 
                         Max(updates.`date`) AS MaxDate 
                  FROM   updates 
                         LEFT JOIN members 
                                ON members.id = updates.consultant 
                  GROUP  BY updates.clientid 
                  ORDER  BY updates.date DESC) u 
              ON customer.id = u.clientid 
WHERE  customer.switchedoff = 'N' 
       AND customer.companyid <> '3' 

1 个答案:

答案 0 :(得分:0)

我认为您的最简单方法是使用substring_index() / group_concat()方法:

SELECT customer.id, 
       customer.name, 
       customer.retainer_value, 
       customer.customer_type, 
       clientdetails.performance, 
       clientdetails.url, 
       members.fullname AS acc_manager, 
       u.maxdate, 
       u.fullname 
FROM   customer 
       LEFT JOIN clientdetails 
              ON clientdetails.id = customer.id 
       LEFT JOIN members 
              ON members.id = customer.consultant_name 
       LEFT JOIN (SELECT updates.clientid, 
                         substring_index(group_concat(m.fullname order by u.date desc separator '|'), '|', 1) as full_name
                         Max(updates.`date`) AS MaxDate 
                  FROM   updates u
                         LEFT JOIN members m
                                ON m.id = u.consultant 
                  GROUP  BY u.clientid
                 ) u 
              ON customer.id = u.clientid 
WHERE  customer.switchedoff = 'N' 
       AND customer.companyid <> '3' ;