SQL多对多计数总和

时间:2013-08-05 11:24:52

标签: mysql sql

我有这张桌子:

id_user id_user2
1      54
1      53
1      53
1      54
1      54
1      55
2      23
2      23
2      20
2      21
2      25
2      25

我想算一下id_userid_user2有多少关系。输出应该是:

id_user id_user2    result
1       54          3
1       53          2
1       55          1
2       23          2
2       20          1
2       21          1
2       25          2

2 个答案:

答案 0 :(得分:4)

您必须使用group by子句

select id_user,id_user2, count(1) as result
from userstab
group by id_user,id_user2

答案 1 :(得分:0)

尝试此查询

select id_user,id_user2,count(id_user2) as result
from TABLE_NAME group by id_user2