0

我似乎无法正确查询此查询。我有这样的表(简化):

person: PersonID, ...other stuff...
contact: ContactID, PersonID, ContactDate, ContactTypeID, Description

我想获取所有与某种类型(或多种类型)有联系但后来没有其他类型的人的列表。一个易于理解的例子:在没有发送感谢卡的情况下检查收到的礼物记录。之前可能已经发送了其他感谢卡(与其他礼物有关),但如果最近收到的礼物(我们会说是 ContactTypeID=12)之后没有发送感谢卡(ContactTypeID=11) ),PersonID 应该在结果集中。另一个示例:邮件列表将由最近选择加入 (12) 而没有选择退出 (11) 的每个人组成。

我的查询尝试是这样的:

SELECT person.PersonID FROM person
INNER JOIN (SELECT PersonID,ContactTypeID,MAX(ContactDate) FROM contact
  WHERE ContactTypeID IN (12,11) GROUP BY PersonID) AS seq
  ON person.PersonID=seq.PersonID
WHERE seq.ContactTypeID IN (12)`

似乎子查询中返回的 ContactTypeID 是表中输入的最后一条记录,无论哪条记录具有最大日期。但我不知道如何解决它。抱歉,之前是否有人问过这个问题(几乎所有问题都有!),但我不知道要搜索什么术语。

4

1 回答 1

1

哇。一个系统来检查谁是好的并发送了谢谢。我想我会在你的名单上...

反正。试一试。这个想法是创建两个视图:第一个视图personId和最近收到的礼物的时间,第二个视图personId和最近发送的感谢。使用 a 将它们连接在一起left outer join以确保包括从未发送过感谢的人,然后添加最近收到的时间和最近的感谢时间之间的比较,以找到不礼貌的人:

select g.personId,
g.mostRecentGiftReceivedTime,
t.mostRecentThankYouTime
from
(
select p.personId,
max(ContactDate) as mostRecentGiftReceivedTime
from person p inner join contact c on p.personId = c.personId
where c.ContactTypeId = 12
group by p.personId
) g
left outer join
(
select p.personId,
max(ContactDate) as mostRecentThankYouTime
from person p inner join contact c on p.personId = c.personId
where c.ContactTypeId = 11
group by p.personId
) t on g.personId = t.personId
where t.mostRecentThankYouTime is null
or t.mostRecentThankYouTime < g.mostRecentGiftReceivedTime;

这是我使用的测试数据:

create table person (PersonID int unsigned not null primary key);

create table contact (
ContactID int unsigned not null primary key,
PersonID int unsigned not null,
ContactDate datetime not null,
ContactTypeId int unsigned not null,
Description varchar(50) default null
);

insert into person values (1);
insert into person values  (2);
insert into person values  (3);
insert into person values  (4);

insert into contact values  (1,1,'2013-05-01',12,'Person 1 Got a present');
insert into contact values  (2,1,'2013-05-03',11,'Person 1 said "Thanks"');
insert into contact values  (3,1,'2013-05-05',12,'Person 1 got another present. Lucky person 1.');

insert into contact values  (4,2,'2013-05-01',11,'Person 2 said "Thanks". Not sure what for.');
insert into contact values  (5,2,'2013-05-08',12,'Person 2 got a present.');

insert into contact values  (6,3,'2013-04-25',12,'Person 3 Got a present');
insert into contact values  (7,3,'2013-04-30',11,'Person 3 said "Thanks"');
insert into contact values  (8,3,'2013-05-02',12,'Person 3 got another present. Lucky person 3.');
insert into contact values  (9,3,'2013-05-05',11,'Person 3 said "Thanks" again.');

insert into contact values  (10,4,'2013-04-30',12,'Person 4 got his first present');
于 2013-05-15T11:33:16.733 回答