2011-12-11 78 views
0

有一個包含所有產品詳細信息的產品表。一個產品可以被提名到不同的人可以投票的熱門表。我只需要計算註冊用戶的投票數。目前它正在統計特定產品的所有投票。我如何克服這個問題?我已經粘貼下面我的SQL代碼:來自多個表的SQL計數和連接

SELECT popular.name, popular.product_id, product.text, product.author, count(  vote.product_id) AS votes 
FROM popular 
LEFT JOIN product ON (product.id = popular.product_id) 
LEFT JOIN vote ON (vote.product_id = popular.product_id) 
where popular.hidden = '1' and 
popular.name in (select registered.name from registered 
where registered.course_id='".$course_id."' and 
registered.section = '".$section."' and 
registered.term = '".$term."') 
GROUP BY popular.product_id 
ORDER BY votes DESC Limit 10 

回答

0

你錯過了票,您的其他表

Select P.ID, P.text, count(v.Product_ID) as votes 
FROM Product PRO 
LEFT JOIN Popular Pop 
    ON PRO.ID = Pop.Product_ID 
LEFT JOIN VOTE V --<-- This is missing 
    on V.Product_ID = Pro.ID 
Group by P.ID, Pro.Text 
order by votes Desc 
+0

我需要稍微修改一下。我只需要通過註冊用戶來計算投票數,但流行的產品可以由任何用戶投票。我怎麼做? – codingNewbie

0
 
SELECT pop.product_id, pd.text, count(vt.product_id) AS votes 
FROM popular pop 
LEFT JOIN product pd ON(pd.product = pop.product_id) 
LEFT JOIN vote vt ON(vt.product_id = pop.product_id) 
WHERE 1 = 1 // or pop.product_id = yourProductId here 
GROUP BY pop.product.id 
ORDER BY vt.votes DESC 

+0

謝謝sooo多!! :D:D – codingNewbie

+0

我需要稍微修改一下。我只需要通過註冊用戶來計算投票數,但流行的產品可以由任何用戶投票。我怎麼做? – codingNewbie

0
SELECT popular.product_id, product.text, count(vote.product_id) AS votes 
FROM popular, product, vote 
WHERE product.id = popular.product_id AND product.id = vote.product_id 
GROUP BY product.id 
ORDER BY votes DESC 

注之間的連接,這查詢不返回有沒有產品票。如果你的數據庫中有這樣的記錄,你應該使用LEFT JOINvote表。