I\'m trying to construct a query that will include a column indicating whether or not a user has downloaded a document. I have a table called HasDownloaded with the followin
@Mark: I understand why the JOIN syntax works, but thanks for the warning. I do think your suggestion is more intuitive. I was curious to see which was more efficient. So I ran a quick test (this was rather simplistic, I'm afraid, over only 14 rows and 10 trials):
In the JOIN condition:
AND HasDownloaded.memberID = @memberID
In the WHERE clause:
WHERE HasDownloaded.memberId IS NULL OR HasDownloaded.memberId = @memberId
It looks like the WHERE clause is ever-so-slightly more efficient. Interesting! Once again, thanks to both of you for your help.
WHERE HasDownloaded.memberId IS NULL OR HasDownloaded.memberId = @memberId
would be the normal way to do that. Some would shorten it to:
WHERE COALESCE(HasDownloaded.memberId, @memberId) = @memberId
You can, as Matt B. shows, do it in your JOIN condition - but I think that's much more likely to confuse folks. If you don't understand WHY moving it to the JOIN clause works, then I'd strongly suggest staying away from it.
Move the condition in the WHERE clause to the join condition.
SELECT Documents.name, HasDownloaded.id FROM Documents
LEFT JOIN HasDownloaded ON HasDownloaded.documentID = Documents.id
AND HasDownloaded.memberID = @memberID
This is necessary whenever you want to refer to a left join-ed table in what would otherwise be the WHERE clause.