0

I have two queries:

1:

select Firstname, Lastname, ContactID from contacts where account = 'The Beatles';

it returns

Firstname | Lastname | ContactID
John        Lennon     Beatle01
Paul        McCartney  Beatle02
Ringo       Starr      Beatle03
The         Other1     Beatle04

My second query:

select contacts.lastname, contacts.firstname,
activities.contactid, activities.completeddate
from contacts, activities 
where activities.contactid=contacts.contactid 
AND completeddate >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND completeddate < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY
order by contacts.lastname asc;

If there is an activity last week it will return something like:

Firstname | LastName | CompletedDate
John        Lennon     2013-08-21 13:06
Paul        McCartney  2013-08-21 15:04

What i essentially want to run is an exception query. I.E. show me the names of the users who did NOT have an activity last week.

So query 3 would return something like:

Firstname | Lastname | ContactID
Ringo       Starr      Beatle03
The         Other1     Beatle04

So essentially i need to show all the users in Query1 who DO NOT exist in query two. I have tried several joins, innerjoins etc.. but all fail.

Can anyone recommend a simple way to do this?

4

3 回答 3

2

对于“异常”查询,请考虑“外部联接”。在这种情况下, aleft outer join会做,但您需要将现有条件移动到on子句中:

select c.lastname, c.firstname, a.contactid, a.completeddate
from contacts c left join
     activities a
     on a.contactid = c.contactid and
        completeddate >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY and
        completeddate < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY
where a.contactid is null
order by c.lastname asc;

最后的检查a.contactid是检查没有匹配 - 这是您的异常报告。

于 2013-08-21T17:33:31.497 回答
0

你可以试试这个:

select Firstname, Lastname, ContactID 
from contacts
where contactid not in (
  select contactid
  from activities
  where completeddate >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
    and completeddate < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY
);
于 2013-08-21T17:46:54.400 回答
0

尝试这个:

select Firstname, Lastname, ContactID 
  from contacts
 where account = 'The Beatles'
   and contactid not in (
       select contactid
         from activities
        where completeddate >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
          and completeddate < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY
       );
于 2013-08-21T17:34:13.743 回答