2011-07-07 84 views
4

我試圖返回產品表中當前用戶未添加且當前用戶尚未查看過的產品結果,然後按最少評論顯示的產品進行排序那些沒有第一個。MySQL加入問題

  • tblUsers

    UserID 
    1 
    2 
    3 
    
  • tblProducts

    ProductID UserID (created) NumberReviews 
    --------- ---------------- ------------- 
    1   1    1 
    2   1    0 
    3   2    1 
    4   1    2 
    5   2    0 
    
  • tblReviews

    ReviewID UserID(reviewed) ProductID 
    -------- ---------------- --------- 
    1  2    4 
    2  1    3 
    3  3    4 
    4  3    1 
    

所以對於2當前用戶我想回到

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

我已經嘗試了許多不同的左的聯接,但無濟於事。有任何想法嗎?

+2

提示:添加名稱的每個表在你的問題,使其更容易與例子/代碼回答。 –

+1

此外,如果您包含一些數據設置代碼,則會得到更快的答覆。 – SWeko

回答

1
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 

如果你不想計數,但使用現場NumberReviews訂購,這是簡單的:

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 
+0

感謝這工作 –

1

嘗試用:

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 
0

東西沿着這些線路可能工作(SQL Server的語法,不知道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 
0

如果我沒有錯過任何東西:

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