MySQL查询自我加入最大日期

时间:2012-04-19 19:06:24

标签: mysql date join max

我有2张桌子,联系和搜索。 “联系人”在他工作的地方有联系人的id和companyid。 “搜索”具有联系人和他所属的公司“联系人可以在2家公司工作。它还有联系人最后一次搜索数据库。 cityid对应于他所在的城市。

我正在寻找每个唯一标识的联系人的lastsearchdate。如何获得所需的输出?

create table contact (id integer primary key auto_increment, companyid integer, contactid integer, unique key(companyid, contactid));
insert into contact (companyid, contactid) values (1,1), (1,2), (2,3);

接触:

id companyid contactid
1  1         1    
2  1         2
3  2         3

create table search (searchid integer primary key auto_increment, companyid integer, contactid integer, cityid integer, lastsearchdate date);
insert into search (companyid, contactid, cityid, lastsearchdate) values (1,1,1,'2012-03-01'), (1,1,2,'2012-04-16'), (2,3,3,'2012-04-01'), (1,1,1,'2012-03-07'), (2,3,4,'2012-04-10'), (1,2,1,'2012-04-01');

搜索:

searchid companyid contactid cityid   lastsearchdate
1        1          1        1        2012-03-01
2        1          1        2        2012-04-16
3        2          3        3        2012-04-01
4        1          1        1        2012-03-07
5        2          3        4        2012-04-10
6        1          2        1        2012-04-01 

期望的输出:

companyid contactid cityid lastsearchdate
1         1         2       2012-04-16
1         2         1       2012-04-01
2         3         4       2012-04-10

到目前为止的查询:

select b.companyid, b.contactid, a.cityid, a.lastsearchdate from search a join contact b
on a.companyid = b.companyid and a.contactid = b.contactid
join search c
on a.companyid = c.companyid and a.contactid = c.contactid and a.lastsearchdate > c.lastsearchdate
group by b.companyid, b.contactid;

1 个答案:

答案 0 :(得分:1)

根据您要查找的内容的描述,这不是您的样本数据所需的输出吗? (不知道为什么你也放弃了下面的记录2和3)

companyid contactid cityid   lastsearchdate    
1          1        2        2012-04-16
2          3        3        2012-04-01
1          1        1        2012-03-07
2          3        4        2012-04-10
1          2        1        2012-04-01 

如果这是正确的,此查询将起作用:

select t1.companyid, t1.contactid, t1.cityid, t1.lastsearchdate
from search t1
where t1.lastsearchdate = (select max(t2.lastsearchdate) from search t2 where t2.companyid =
t1.companyid and t2.contactid = t1.contactid and t2.cityid = t1.cityid);