2011-12-21 72 views
1

我有三個表:如何解決這個LEFT JOIN查詢?

  • 產品(產品編號,名稱)
  • 評論(COMMENT_ID,PRODUCT_ID,USER_ID,評論,POST_DATE)
  • 書籤(USER_ID,PRODUCT_ID,read_date)

對於產品表中的每個product_id,我希望檢索具有相同product_id且其post_date值大於共享此product_id的bookmarks表中的行的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 

這不會給我預期的結果。我如何修改它以使其符合我的要求?

回答

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 

UPDATE GROUP BY c.product_id改爲GROUP BY p.product_id

+0

看起來還在發生。您的查詢在約475K行的產品表上爲我提供了4行結果。 comment_count值也是不正確的(當有多個產品有多個註釋時,我得到三個評論數爲0,一個評論數爲1)。 – jela 2011-12-21 16:50:51

+0

'post_date'或'read_date'是可空的嗎? – a1ex07 2011-12-21 16:59:04

+0

其實comment_count值是正確的,我在評估它們時犯了一個錯誤。 GROUP BY p.product_id而不是c.product_id是否正確? – jela 2011-12-21 17:03:29

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