0
私は2つのテーブル、連絡先と検索している。 「連絡先」には連絡先のIDとcompanyidがあります。 「検索」にはcontactidがあり、彼が所属するcompanyidは連絡先が2社で働くことができます。連絡先がデータベースを最後に検索したこともあります。 cityidは彼が働いていた都市に対応しています。MySQLのクエリ自己最高の日付のために参加
私はすべての一意に識別された連絡先の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,1と2,3は二度現れてはいけません。 1,1と1,2と2,3は固有の接点です。 – ThinkCode
グループをt1.companyid、t1.contactidで追加します。私が探している3つの固有のレコードを提供していますが、レコード2,3は最大の日付を表示していません。奇妙な。 – ThinkCode
市区町村が連絡先IDの一部でない場合、クエリから「and t2.cityid = t1.cityid」を削除すると、望ましい結果が得られます。 – rwalker