2013-08-21 194 views
0

我有兩個疑問: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; 

如果有n活動上週它將返回類似於:

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 

所以基本上我需要顯示在查詢1所有用戶誰不查詢的兩個存在。 我嘗試過幾個連接,innerjoins等等,但都失敗了。

任何人都可以推薦一個簡單的方法來做到這一點?

回答

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的最後檢查是檢查不匹配 - 這是你的異常報告。

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 
     ); 
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 
);