2011-06-11 112 views
0

我希望返回自指定日期以來沒有記錄任何訂單的任何分支機構。通過這個查詢應該簡單易行。SQL腦凍結

select * from affiliate where 
idUser not in ( 
    select idAffiliate from Orders 
    where orderDate > '06/01/11' 
) 

會員表有一個idUser字段,它是Orders表的idAffiliate的外鍵。即使我知道自從本月初以來,我有幾十個沒有下訂單的分支機構,但上述內容不會返回任何記錄。如果我將日期更改爲'07/01/11' - 所有會員記錄都會返回(顯然),但如果沒有其他情況,則驗證我使用的是正確的實體名稱。

非常感謝

+0

是訂購日期字符串類型的?如果是這樣,我認爲你應該使用ansi日期格式。 YYYYMMDD。 – NickD 2011-06-11 13:15:58

+0

您的日期是以YY/MM/DD(或任何奇怪的格式)解析的。 – 2011-06-11 13:17:30

+0

日期類型爲'smalldatetime'。例如:2008-01-28 15:06:00 – justSteve 2011-06-11 13:29:41

回答

4

看起來好像你必須在嵌套查詢中將idAffiliate更改爲idUser。 ,更好地利用EXISTS或NOT EXISTS,而不是在這種情況下

select * from affiliate a 
where not exists ( 
    select 1 from Orders where orderDate > '06/01/11' 
    and Orders.idUser = a.idUser 
) 
+0

Thankx - 只是爲了檔案...它應該是'和Orders.idAffiliate = a.iduser' – justSteve 2011-06-11 13:34:17

0

使用左連接:

select a.* 
from affiliate a 
left join Orders o 
    on a.idUser= o.idAffiliate 
    and o.orderDate > '06/01/11' 
where o.idAffiliate is null