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
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:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您缺少投票和其他表之间的连接
You're missing a join between votes and your other tables
请注意,此查询不会返回没有投票的产品。如果您的数据库中有此类记录,您应该
LEFT JOIN
与vote
表。Note that this query does not return products having no votes. If there are such records in your DB, you should
LEFT JOIN
withvote
table.