Lloyd S
Lloyd S

Reputation: 129

MySQL join issue

I am trying to return the results of the products in the product table that were not added by the current user and that the current user has not already reviewed, then sort by the products that have had the least reviews showing those with none first.

So for a current user of 2 I want to return

Product ID
----------
2
1

I have tried a number of different left joins but to no avail. Any ideas?

Upvotes: 4

Views: 84

Answers (4)

Andriy M
Andriy M

Reputation: 77737

If I didn't miss anything:

SELECT
  p.ProductID
FROM tblProducts p
  LEFT JOIN tblReviews r ON p.ProductID = r.ProductID AND r.UserID = @UserID
WHERE p.UserID <> @UserID
  AND r.ReviewID IS NULL
ORDER BY p.NumberReviews

Upvotes: 0

ypercubeᵀᴹ
ypercubeᵀᴹ

Reputation: 115650

SELECT p.*
     , COUNT(r.ProductID) AS reviews
FROM tblProducts AS p
  LEFT JOIN tblReviews AS r
    ON r.ProductID = p.ProductID
WHERE UserID <> @currentUser
  AND NOT EXISTS
    ( SELECT *
      FROM tblReviews ru
      WHERE ru.ProductID = p.ProductID
        AND ru.UserID = @currentUser
    ) 
GROUP BY p.ProductID
ORDER BY reviews ASC

If you don't want to count but use the field NumberReviews for ordering, it's simpler:

SELECT p.*
FROM tblProducts AS p
WHERE UserID <> @currentUser
  AND NOT EXISTS
    ( SELECT *
      FROM tblReviews ru
      WHERE ru.ProductID = p.ProductID
        AND ru.UserID = @currentUser
    ) 
ORDER BY NumberReviews ASC

Upvotes: 1

SWeko
SWeko

Reputation: 30932

Something along these lines might work (sql server syntax, not sure about mysql)

Select productID 
  from Users u 
    -- all products not created by user
    inner join Products p on p.UserID != u.UserID 
    -- that were reviewed by the user. NOT!
    left outer join Reviews r on p.ProductID = r.ProductID and r.UserID = u.UserID
  where r.ReviewID is null
    and User = CurrentUser

Upvotes: 0

Tudor Constantin
Tudor Constantin

Reputation: 26871

Try with:

SELECT u.*, p.*, r.* FROM users u 
   LEFT JOIN products p ON p.userId <> u.userID 
   LEFT JOIN reviews r ON ( r.productId = p.ProductID AND r.UserID = u.userID)
GROUP BY p.productID ORDER BY p.NumberReviews

Upvotes: 1

Related Questions