计算每个帖子的投票数
我们目前正试图进行一个简单的(?)SQL 查询。
我们有这两个表:
create table `post` (
`id` integer primary key
)
create table `vote` (
`id` integer primary key,
`post_id` references `post`.`id`, // Well ok, it's a foreign key then...
`value` int // 1 for a positive vote, or zero for a negative one
)
我们正在尝试构建一个选择,对于每个帖子,返回正面和负面投票的数量:SELECT post.id,
虽然这对于子选择来说并不难做到,但当我们尝试在不使用子选择但使用 join
的情况下做到这一点时,挑战就开始了。我们使用左外连接
,当帖子只有赞成票或反对票时就会出现问题。
虽然我理解这个问题,但我无法弄清楚如何仅使用 join
来做到这一点,但我相信它可以在没有子选择的情况下完成。你会怎么做?
(好吧,我没有包含我当前的查询,这样它就不会引导您走向错误的方向......)
We're currently stuck trying to make a simple (?) SQL query.
We have these two tables:
create table `post` (
`id` integer primary key
)
create table `vote` (
`id` integer primary key,
`post_id` references `post`.`id`, // Well ok, it's a foreign key then...
`value` int // 1 for a positive vote, or zero for a negative one
)
We're trying to build a select that would, for each post, return the number of positive and negative votes: SELECT post.id, <positive count>, <negative count> ...
While this is not hard to do with sub-selects, the challenge begins when we try to do this without sub-selects, but with join
. We're using left outer join
, and the problems arise when a post has only positive or negative votes.
While I understand the problem, I can't figure out how to do that only with join
, yet I'm confident it can be done without sub-selects. How would you do that ?
(Well, I did not include my current query, so that it won't guide you to the wrong direction...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以前的答案是垃圾,我忘了
GROUP
。这是使用CASE
的替代方案,我认为它可以处理NULL
情况(因为WHEN
子句将为NULL
)但毕竟你可能需要使用COALESCE
...:以前(不正确)的答案:
Previous answer was rubbish, I forgot to
GROUP
. Here's an alternative that usesCASE
, I THINK it handles theNULL
case (since theWHEN
clause will beNULL
) but you may need to useCOALESCE
after all...:Previous (incorrect) answer: