如何修复此LEFT JOIN查询?

时间:2011-12-21 16:19:26

标签: mysql

我有三张桌子:

  • 产品(product_id,title)
  • 评论(comment_id,product_id,user_id,comment,post_date)
  • 书签(user_id,product_id,read_date)

对于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

这并没有给我预期的结果。如何修改它以使其按照我的要求进行操作?

2 个答案:

答案 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