6

我的数据库中有两张表,一张用于保存用户信息(users_table),另一张用于跟踪朋友

用户表:

id    username      avatar  
1         max       max.jpg  
2         jack      jack.jpg  

朋友表:

id    u1_id      u2_id  
1         1          2  
2         1          3  

在每个用户个人资料中,我都会显示他/她的朋友列表

这是我的查询

select u.id,
    u.username,
    u.avatar
from friends_table f
join users_table u on f.u1_id = u.id || f.u2_id = u.id
where u.id <> $profile_id
    and (f.u1_id = $profile_id || f.u2_id = $profile_id)

此查询选择个人资料所有者的朋友 ($profile_id)

并将他们与用户表连接起来以获取每个朋友的用户名和头像

现在我想计算每个朋友和个人资料所有者之间的共同朋友是否可以在一个查询中进行,或者我应该为每个已建立的朋友做一些长且可能很慢的查询(这只是一个例子,它可能有一些语法错误 ):

       foreach ( $friends_list_query_resul as $qr ){
       $friend_id = $qr['id'];

       $mutual_count = mysql_query
    ( "select count(*) from friends_table where 
    ($u1_id = $friend_id || $u2_id = $friend_id )
               && 


    ( $u1_id IN ( SELECT `u1_id`,`u2_id` from friends_table where
     ($u1_id = $profile_id || $u2_id = $profile_id ) )

||

      $u2_id IN ( SELECT `u1_id`,`u2_id` from friends_table where
     ($u1_id = $profile_id || $u2_id = $profile_id ) )


       ")
        }
4

4 回答 4

1

您的第一个查询也可以写成:

select distinct u.id,
        u.username,
        u.avatar
    from users_table u where u.id in 
        (select case when u1_id=$profile_id then u2_id else u1_id end 
        from friends_table f where case when u1_id=$profile_id 
        then u1_id else u2_id end =$profile_id);

可以用类似的方式将共同好友查询写成单个查询:

select u.id, (select count(f.id) from friends f where 
    case when f.u1_id=u.id then u2_id else u1_id end in 
        (select distinct case when u1_id=$profile_id then u2_id else u1_id end 
        from friends where case when u1_id=$profile_id then u1_id else u2_id 
        end =$profile_id) 
    and u1_id=u.id or u2_id=u.id and 
    (u1_id <> $profile_id and u2_id <> $profile_id)) 
as mutual_frnds from user u where u.id <> $profile_id;

但您可能希望在使用前对其中任何一个进行性能测试。

于 2012-05-20T08:44:55.743 回答
1

您只需要一个查询:

select id, username, avatar, -- ...
(
  select count(*)
  from friends_table f1
  inner join friends_table f2 on f1.u2_id = f2.u1_id and f2.u2_id = f1.u1_id
  where f1.u1_id = users_table.id
)
as mutual_friend_count
from users_table

子查询的含义是:

给我用户参与的“朋友的朋友”关系的计数,使得第一个朋友关系的目标是第二个朋友关系的来源,第二个朋友关系的目标是第一个朋友关系的来源一。

于 2012-05-22T22:05:24.377 回答
0

首先,我不明白为什么要这么复杂的查询来检索用户的朋友......应该简单地通过这个查询来实现:

select u.id,
    u.username,
    u.avatar
from friends_table f
left join users_table u on f.u2_id = u.id
where f.u1_id = $profile_id

说明:登录用户是 id 相同的用户f.u1_id。因此我们只选择 id 在 中的朋友f.u2_id

然后,要计算我朋友的共同朋友,我们可以使用如下查询:

select count(*) as mutual_count, f.u1_id as mutual_friend_id
from friends_table f
where f.u1_id IN (select f.u2_id from friends_table where f.u1_id = {$profile_id})

其中 $profile_id 是登录用户的 ID...

它是否正确?

于 2012-05-17T10:49:28.070 回答
0

我决定为表中的每个朋友关系添加两行。

id    u1_id      u2_id  
1         10         20  
2         20         10

它使这个过程更容易和更快。

于 2012-05-24T14:48:55.420 回答