Question

I'm having a problem limiting the left result set with a WHERE clause, even when I put the same condition in the subquery that forms the right result set. Here's an example:

SELECT shareItems.*, likes FROM shareItems LEFT JOIN
   (SELECT users_X_shareItems.itemID, COUNT(users_X_shareItems.userID) AS 'likes'
    FROM users_X_shareItems, shareItems WHERE shareItems.itemType = 2 AND
    users_X_shareItems.liked = 1
    GROUP BY users_X_shareItems.itemID) AS likeTable
ON shareItems.itemID = likeTable.itemID AND shareItems.itemType = 2

Despite my specifying shareItems.itemType = 2 in both queries, it's ignored. Anybody know why? Thanks.

Was it helpful?

Solution

If you want to limit the left side of your LEFT JOIN, you need to put the condition as WHERE, not on the JOIN (that will only limit the right side):

 ON shareItems.itemID = likeTable.itemID
 WHERE shareItems.itemType = 2

OTHER TIPS

They are not ignored, they are being applied BEFORE the records from the inner side of the join which have no match in the outer table have been added to the result set.
because the predicate is part of the join, it is applied as part of the join, then after that happens, all records form the inner side that have no match are added back in.. Since there is no match, the predicate on the outer side cannot (by definition of OUTRER it cannot) be applied then. All such records, because there is no match in the outer table, will of course have null values in any attributes which should have come from that table anyway, so the predicate can't be applied at that point anyway.

Move the predicate condition to a WHERE clause, then it will be applied after the outer join, and will do what you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top