使用MySQL获取关注者并在一个查询中关注

时间:2011-02-24 15:55:22

标签: php mysql sql

好吧,我想说我正在制作像twitter这样的社交网络。 我有一张名为“社交”的表格,在这里我们将社交内容放在哪里。

example me ( uid = 1 )
friend1 ( uid = 2 )
friend2 ( uid = 3 )

表格

SID AUID BUID
1   1    2
2   1    3
3   2    1

我们在这里获得的信息是

user id 1(me) is following 2
user id 1(me) is following 3
user id 2 is following 1(me)

问题是:我们可以在一个查询中执行以下两个查询吗?

function CountFollowers($uid){
    $count = $this->fetch("SELECT COUNT(BUID) as followers
                                   FROM social WHERE BUID = :uid", 
    array( 'uid' => $uid));
    return $count;
}

function CountFollowing($uid){
    $count = $this->fetch("SELECT COUNT(AUID) as following
                                   FROM social WHERE AUID = :uid", 
    array( 'uid' => $uid));
    return $arrayofdata;
}

感谢您查看

4 个答案:

答案 0 :(得分:5)

这会为您提供以下跟随者和关注者数量的两列

SELECT (SELECT COUNT(BUID) as count FROM social WHERE BUID = :uid) as Followers
  , (SELECT COUNT(AUID) as count FROM social WHERE AUID = :uid) as Following

答案 1 :(得分:2)

您需要UNION吗?

SELECT 'followers' as `type`, COUNT(BUID) as count FROM social WHERE BUID = :uid
UNION
SELECT 'following' as `type` COUNT(AUID) as count FROM social WHERE AUID = :uid

或者你可以用不同的方式做到这一点:

SELECT COUNT(CASE 
WHEN BUID =:uid THEN 1
END) as  Followers,
COUNT(CASE
WHEN AUID=:uid THEN 1
END) as Following
 FROM social WHERE BUID = :uid OR AUID = :uid

答案 2 :(得分:2)

SELECT
  COUNT(DISTINCT NULLIF(AUID, :uid)) AS MyFollowers,
  COUNT(DISTINCT NULLIF(BUID, :uid)) AS MeFollowing
FROM atable
WHERE :uid IN (AUID, BUID)

如果(AUID, BUID)对是唯一的,则不需要DISTINCT

SELECT
  COUNT(NULLIF(AUID, :uid)) AS MyFollowers,
  COUNT(NULLIF(BUID, :uid)) AS MeFollowing
FROM atable
WHERE :uid IN (AUID, BUID)

答案 3 :(得分:0)

Select Sum( Case When AUID = $uid Then 1 Else 0 End ) As Following
    , Sum( Case When BUID = $uid Then 1 Else 0 End ) As Followers
From Table
Where AUID = $uid
    Or BUID = $uid