一个是很多关系,得到最新的一排

时间:2013-01-04 07:07:56

标签: mysql sql join group-by

lead_sp_id  sp_id   phone
1           5       111     
2           5       222     
3           5       333 
4           3       444     
5           3       555     
6           3       666     
7           3       777 
8           5       888 

act_id      lead_sp_id sp_id   act_time
1           1          5       2012-12-31 14:20:49      
2           1          5       2012-12-30 14:20:49      
3           2          5       2012-12-29 14:20:49  
4           2          5       2012-12-31 14:20:49  
5           2          5       2012-12-28 14:20:49   
6           4          3       2012-12-31 14:20:49  
7           4          3       2012-12-28 14:20:49  
8           4          3       2012-12-25 14:20:49  

我希望得到的结果是

phone | lead_sp_id | sp_id | act_time
111   | 1          | 5     | 2012-12-31 14:20:49
222   | 2          | 5     | 2012-12-31 14:20:49

现在我知道我必须使用连接语句并且使用常规连接语句只会给我太多结果,包括旧日期我想要做的就是根据每个电话号码获取最新的act_name和act_time sp_id。

2 个答案:

答案 0 :(得分:0)

尝试此查询

SELECT 
    * 
FROM table1 as t1 
INNER JOIN (
            SELECT 
                *
            FROM 
            table2      
            INNER JOIN (SELECT MAX(act_id) FROM table2 GROUP BY act_id) 
            as r on r.act_id = table2.act_id
) as t2 on t1.sp_id = t2.sp_id

答案 1 :(得分:0)

试试这个:

SELECT a.phone, b.lead_sp_id, b.sp_id, b.act_time 
FROM leadsptable a 
INNER JOIN (SELECT a.lead_sp_id, a.sp_id, a.act_time 
            FROM acttable a 
            INNER JOIN (SELECT lead_sp_id, MAX(act_time) act_time 
                        FROM acttable GROUP BY lead_sp_id
                      ) b ON a.lead_sp_id = b.lead_sp_id AND a.act_time = b.act_time 
            ) b ON a.lead_sp_id = b.lead_sp_id AND a.sp_id = b.sp_id