MySQL - 根据另一个查询的结果过滤结果(显示区别)

时间:2013-08-21 17:26:14

标签: mysql

我有两个问题:

1:

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

它返回

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

我的第二个问题:

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;

如果上周有活动,它将返回如下内容:

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

我本质上想要运行的是异常查询。 I.E.告诉我上周没有活动的用户的姓名。

因此查询3将返回类似于:

的内容
Firstname | Lastname | ContactID
Ringo       Starr      Beatle03
The         Other1     Beatle04

基本上我需要向Query1中显示查询二中不存在的所有用户。 我尝试了几个连接,内连接等等。但都失败了。

有人可以推荐一种简单的方法吗?

3 个答案:

答案 0 :(得分:2)

对于“异常”查询,请考虑“外部联接”。在这种情况下,left 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的最终检查是检查没有匹配 - 这是您的例外报告。

答案 1 :(得分: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
       );

答案 2 :(得分: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
);