Help with a WHERE on a LEFT JOIN SQL Query

后端 未结 3 1646
自闭症患者
自闭症患者 2020-12-28 16:20

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

相关标签:
3条回答
  • 2020-12-28 16:38

    @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
    
    • Client processing time: 4.6
    • Total execution time: 35.5
    • Wait time on server replies: 30.9

    In the WHERE clause:

    WHERE HasDownloaded.memberId IS NULL OR HasDownloaded.memberId = @memberId
    
    • Client processing time: 7.7
    • Total execution time: 27.7
    • Wait time on server replies: 22.0

    It looks like the WHERE clause is ever-so-slightly more efficient. Interesting! Once again, thanks to both of you for your help.

    0 讨论(0)
  • 2020-12-28 16:44
    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.

    0 讨论(0)
  • 2020-12-28 16:46

    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.

    0 讨论(0)
提交回复
热议问题