I have three tables:
- products (product_id, title)
- comments (comment_id, product_id, user_id, comment, post_date)
- bookmarks (user_id, product_id, read_date)
For each product_id in the products table, I wish to retrieve the number of comments with the same product_id, and whose post_date value is greater than the read_date value for the row in the bookmarks table that shares this product_id, and has user_id=22.
If such a row does not exist in the bookmarks table, I want to retrieve the total number of comments for that product_id regardless of read_date.
So far I have
SELECT p.product_id, COUNT( c.comment_id ) comment_count
FROM products p
LEFT JOIN bookmarks b, comments c ON b.product_id = c.product_id
AND b.user_id =22
AND (
c.post_date > b.read_date
)
AND p.product_id = c.product_id
GROUP BY c.product_id
ORDER BY comment_count DESC
This does not give me the expected results. How can I modify it to make it do what I want?
Will it work for you ?
UPDATE
GROUP BY c.product_idchanged toGROUP BY p.product_id