Help with a WHERE on a LEFT JOIN SQL Query

后端 未结 3 1647
自闭症患者
自闭症患者 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题