sql: want to select record from table 1, based on matching (or no matching) record in table2
I have two tables. They are linked together with a userid. What i wanted do is check if there's a linked record in table 2 AND if a date field in that table is older then a certain time OR if there's no linked record in the 2nd table.
I thought i wanted a left join, but it's ignoring the date field. If there are no records in the 2nd table, then i want to ignore th开发者_如何学Pythone 2nd table. But if there is a matching record in the 2nd table and the date is outside of my range, then i dont want to select those records.
SELECT FirstName, Email, u.userid FROM u
LEFT JOIN uevh
ON u.UserID = uevh.UserID AND uevh.LastEmailed < GETDATE()-14
WHERE u.ConfirmedEmail = 0
if i run that, and there's a record in the uevh table that's less then 14 days old, i dont want a record returned, but it's returning a record regardless of the date.
SELECT u.FirstName
, u.Email
, u.userid
FROM u
WHERE NOT EXISTS
( SELECT *
FROM uevh
WHERE u.UserID = uevh.UserID
AND NOT (uevh.LastEmailed < GETDATE()-14)
)
AND u.ConfirmedEmail = 0
or:
SELECT u.FirstName
, u.Email
, u.userid
FROM u
WHERE ( EXISTS
( SELECT *
FROM uevh
WHERE u.UserID = uevh.UserID
AND uevh.LastEmailed < GETDATE()-14
)
OR NOT EXISTS
( SELECT *
FROM uevh
WHERE u.UserID = uevh.UserID
)
)
AND u.ConfirmedEmail = 0
or:
SELECT u.FirstName
, u.Email
, u.userid
FROM u
LEFT JOIN uevh
ON u.UserID = uevh.UserID
WHERE u.ConfirmedEmail = 0
AND ( uevh.LastEmailed < GETDATE()-14
OR uehv.UserID IS NULL
)
You could try something like this. This is untested but should work.
Declare @date datetime;
Set @date='20110101';
Select *
from tbl1
Left outer join tbl2 on tbl1.Id =tbl2.Id
and @date > coalesce(tbl2.date,dateadd(day,1,@date));
精彩评论