在不同条件下计算 2 列

Count 2 columns on different conditions

我有这个数据集:

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'

现在的问题是,有没有其他方法可以做到这一点?或者这是实现此目标的最佳方法?

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

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 所指出的,您可以使用索引来优化性能。

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

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