[英]SQL count and join from multiple tables
There is a product table which contains all the product details. 有一个产品表,其中包含所有产品详细信息。 A product can be nominated to the popular table from where different people can vote on it.
可以将一种产品提名到流行表中,从那里不同的人可以对其进行投票。 i need to count only the votes of registered users.
我只需要计算注册用户的票数。 Currently it is counting all the votes that a particular product has.
目前,它正在计算特定产品的所有票数。 How do i overcome this problem?
我该如何克服这个问题? i have pasted my sql code below:
我在下面粘贴了我的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
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
You're missing a join between votes and your other tables 您缺少选票和其他表格之间的连接
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
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
Note that this query does not return products having no votes. 请注意,此查询不会返回没有投票的产品。 If there are such records in your DB, you should
LEFT JOIN
with vote
table. 如果您的数据库中有此类记录,则应使用
vote
表LEFT JOIN
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.