2012-12-08 82 views
0

表 - 朋友MySQL友谊关系计数?

friend_id  | friend_one | friend_two | role 
+--------------------------------------------------------------------------------------------+ 
|1: 44    34    34   me 
|2: 45    35    35   me 
|3: 46    35    34   fri 
+--------------------------------------------------------------------------------------------+ 

我需要来算,谁是跟随和谁是追随者..这是相当多了,我已经得到了下面的一些答案,但大多只是给我静态的电话号码,但感谢你这么远为了帮助,它给了我一个开始的地方。

+0

这个问题与应用程序代码没有任何关系;考虑删除所有这样的代码,只留下编辑后的SQL – Bohemian

+0

@ Bohemian。 –

+1

你应该删除所有的php相关的东西,并恢复刚删除的表格数据 –

回答

0

似乎要简单:

select friend_one, count(*) as count 
from friends 
where friend_one != friend_two -- fyi such rows shouldn't exist 
group by friend_one; 

,如果你想为特定用户的数量,这样做:

select count(*) as count 
from friends 
where friend_one != friend_two -- fyi such rows shouldn't exist 
and friend_one = $uid 

关于friend_one != friend_two我的意见是,因为你似乎有“自动自我朋友“条目为每个用户。这是一个不好的主意,恕我直言,因为它不增加任何价值 - 考虑没有这样的行。

+0

认为这是最好的粘贴在这里。我试过这个,即使我跟随3个用户,它也会返回一个常数1。 pastebin.com/EBcWUMrc如果我尝试这个pastebin.com/cSpPJXNc我得到一个常量3,我做错了什么? –