我有三张桌子:
对于products表中的每个product_id,我希望检索具有相同product_id的注释数,并且其post_date值大于共享此product_id的书签表中行的read_date值,并且具有user_id = 22。
如果书签表中不存在这样的行,我想检索该product_id的注释总数,而不管read_date。
到目前为止我已经
了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
这并没有给我预期的结果。如何修改它以使其按照我的要求进行操作?
答案 0 :(得分:1)
它会对你有用吗?
SELECT p.product_id,
COUNT(CASE
WHEN b.read_date IS NOT NULL AND c.post_date >b.read_date THEN c.comment_id
WHEN b.read_date IS NULL THEN c.comment_id
ELSE NULL //optional, CASE has default ELSE NULL
END) as comment_count
FROM products p
LEFT JOIN bookmarks b ON (b.product_id = p.product_id AND b.user_id=22)
LEFT JOIN comments c ON (p.product_id = c.product_id)
GROUP BY p.product_id
ORDER BY comment_count DESC
<强>更新强>
GROUP BY c.product_id
已更改为GROUP BY p.product_id
答案 1 :(得分:0)
也许这对你有用,或至少指向正确的方向。
SELECT p.product_id COUNT( c.comment_id ) comment_count
FROM products p
LEFT JOIN comments c on c.product_id = p.product_id
LEFT JOIN bookmarks b on b.product_id = c.product_id
WHERE (p.product_id IN (
SELECT *
FROM bookmarks b
WHERE b.user_id = 22
)
AND
c.post_date > b.read_date
)
OR
p.product_id NOT IN (
SELECT *
FROM bookmarks b
WHERE b.user_id = 22
)
GROUP BY c.product_id
ORDER BY comment_count DESC