2

私は人々がお互いに「友達」になることができるモデルを持っています(友情)。双方向の友情を2回カウントせずに、人が友だちであり、友だちである人の数をどのように照会できますか?

次に例を示します。

1 -> 2
2 -> 1
1 -> 3
4 -> 1

3人の友達がいる#1として登録したい

友情(id、person_id、friend_id)

4

4 に答える 4

2
Select
  count(distinct(f.user_id + f.friend_id))
From
  Friends f
Where
  f.user_id = 1 or f.friend_id = 1

ただし、次のようなことを行う方が効率的かもしれません。

Select
  Count(*)
From (
  Select friend_id From Friends f Where f.user_id = 1
  Union
  Select user_id From Friends f where f.friend_id = 1
) as a

ユーザーテーブルも想定して、全員の友達数を取得するには、次のようにします。

Select
  u.user_id,
  count(distinct f.user_id + f.friend_id)
From
  Users u
    Left Outer Join
  Friends f
    On u.user_id = f.user_id Or u.user_id = f.friend_id

またはを使用して参加すると、通常はクエリが遅くなります。他の方法は次のようになります。

Select
  u.user_id,
  count(distinct f.friend_id)
From
  Users u
    Left Outer Join (
      Select user_id, friend_id from Friends
      Union All
      Select friend_id, user_id from Friends
  ) f
    On u.user_id = f.user_id

Union AllをUnionに変更して、どちらが速いかわからない、明確なものを取り除くことができます。

于 2012-11-08T23:50:43.643 に答える
0
select person_id, sum(ct) friend_count
from (select person_id, count(*) ct from friends
      group by person_id
      UNION ALL
      select f1.friend_id, count(*) ct
      from friends f1
      left join friends f2 on f1.person_id = f2.friend_id
      where f2.person_id is null
      group by f1.friend_id) u
group by person_id
于 2012-11-09T00:36:54.533 に答える
0
select id, count(*)
from
  (select id, person_id as p1, friend_id as p2 from friendships
   union select id, person_id as p2, friend_id as p1 from friendships) fs
group by id
于 2012-11-08T23:55:29.570 に答える
0
Select distinct f1.id,count(f1.id) 
from friendships f1 
join friendships f2 on f1.person_id = f2.friend_id
Group by f1.id
于 2012-11-08T23:52:09.013 に答える