0

我有 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;
4

1 回答 1

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);
于 2012-04-19T19:49:05.090 回答