在不同条件下计数2列

时间:2015-08-15 11:05:05

标签: mysql sql social-networking

我有这个数据集:

id  uid    follows_uid  status      
1   1       2           ACTIVE
2   1       3           ACTIVE
3   3       1           ACTIVE
4   4       1           ACTIVE
5   2       1           ACTIVE

给予uid我想计算有多少用户关注,以及有多少用户(给定用户)。

结果集将为:

following     followers
2             3

这是执行工作的查询:

SELECT COUNT(*) as following, 
    (SELECT COUNT(*) FROM user_followers where follows_uid = 1  ) as followers
FROM user_followers
WHERE uid = 1 and `status` = 'ACTIVE'

现在的问题是,有没有其他方法可以完成这项工作?或者这是实现这一目标的最佳方式吗?

3 个答案:

答案 0 :(得分:2)

如果在uidfollows_uid上有单独的索引,那么我相信使用子查询是检索单独计数的最快方法,因为每个查询都会利用索引来检索计数。

答案 1 :(得分:1)

这是实现它的另一种方式。

select following.*, followers.* from
(select count(uid) from user_followers where uid = 1) following,
(select count(follows_uid) from user_followers where follows_uid = 1) followers;

而且,为了回答你的问题,你的子查询方法实际上是实现它的最佳方法。正如@FuzzyTree所指出的,您可以使用索引来优化您的性能。

答案 2 :(得分:1)

SELECT
  IFNULL(SUM(IF(uid = 1, 1, 0)), 0) as following, 
  IFNULL(SUM(IF(follows_uid = 1, 1, 0)), 0) as followers
FROM user_followers
WHERE (uid = 1 OR follows_uid = 1) 
AND `status` = 'ACTIVE';

Click here to see SQL Fiddle