0
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

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

4

2 回答 2

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
于 2013-01-04T07:21:27.610 回答
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
于 2013-01-04T07:24:25.587 回答