我有 2 张桌子,联系人和搜索。“联系人”包含联系人的 ID 和他工作的公司 ID。'搜索'有他所属的contactid和companyid,因为一个联系人可以在2家公司工作。它还有最后一次联系人搜索数据库的时间。cityid 对应他工作的城市。
我正在寻找每个唯一标识的联系人的最后搜索日期。如何获得所需的输出?
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;