2011-12-11 46 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表。