2012-04-19 8 views
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

あなたが探しているものの説明に基づいて、これはサンプルデータの望ましい出力ではないでしょうか? (あなたも下記からレコード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); 
+0

コンタクトを一意彼らはで働いている会社によって識別されます。したがって、1,1と2,3は二度現れてはいけません。 1,1と1,2と2,3は固有の接点です。 – ThinkCode

+0

グループをt1.companyid、t1.contactidで追加します。私が探している3つの固有のレコードを提供していますが、レコード2,3は最大の日付を表示していません。奇妙な。 – ThinkCode

+1

市区町村が連絡先IDの一部でない場合、クエリから「and t2.cityid = t1.cityid」を削除すると、望ましい結果が得られます。 – rwalker