按 + 分组给定并在同一输出中获得投票
我有一个带有投票的表,其中数据以这种格式写入:
id_user|id_user2|value
1|2|-1
1|3|1
5|3|1
2|1|-1
id_user 是投票的用户,id_user2 是获得投票的用户,值表示他是否获得了赞成票或反对票。好吧,我的问题是,我想展示每个用户在相同输出中给予和获得投票的立场。下面是我希望上面输入的输出的样子:
id_user|given|gotten
1|0|-1
2|-1|-1
3|0|2
5|1|0
我不知道如何做到这一点,我只知道如何用两个单独的查询来显示它。在这种情况下,它将是:
SELECT id_user2,SUM(value) FROM `table` GROUP BY id_user2
和
SELECT id_user,SUM(value) FROM `table` GROUP BY id_user
I have table with votes where data is written in this format:
id_user|id_user2|value
1|2|-1
1|3|1
5|3|1
2|1|-1
id_user is user who voted, id_user2 is user who got vote and value represents if he got positive or negative vote. Well and my problem is that i would like to show how stands each user in giving and getting votes in same output. Below is how i would like output from above input would look:
id_user|given|gotten
1|0|-1
2|-1|-1
3|0|2
5|1|0
I don't know how to do this, i just know how i can show this with two separate queries. In this case it would be:
SELECT id_user2,SUM(value) FROM `table` GROUP BY id_user2
and
SELECT id_user,SUM(value) FROM `table` GROUP BY id_user
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需加入查询即可:
注意,如果用户没有投票或没有获得投票,则不会为他返回任何内容。如果您需要这些情况的结果,请使用完整外连接进行连接,即使左表或右表中没有与您的条件匹配的行。
如果没有给予或获得投票,您将得到空值。
Simply join the queries :
N.B. if the user did not give or did not get votes, it won't return anything for him. If you need a result for these cases, use a full outer join to join even if there are not rows matching your condition in the left or right table.
You will get null values where there are no given or gotten votes.