是否可以在同一查询中计算两列

时间:2011-02-27 13:11:47

标签: mysql

假设我有以下表结构:

t1
-------------
id // row id
userID_follower // this user is a follows another member
userID_following  // other member that this user 

是否可以运行单个查询以组合以下两者:

  1. 此人关注的用户数

      

    从t1 WHERE userID_follower =“。$ myID”中选择COUNT(id)。   。“

  2. 有多少用户关注此人

      

    从t1选择COUNT(id)WHERE userID_following =“。$ myID。”

  3. 感谢。

4 个答案:

答案 0 :(得分:50)

在MySql中,您可以在条件上使用SUM()函数,因为错误条件等于0,而真条件等于1

SELECT SUM(userID_follower = $myID) AS followerCount,
   SUM(userID_following = $myID) AS followingCount
FROM t1
WHERE userID_follower = $myID
   OR userID_following = $myID

答案 1 :(得分:10)

更多Hoyle(ISO)解决方案将使用Case表达式:

Select Sum( Case When userID_follower = $myID Then 1 Else 0 End ) As followerCount
    , Sum( Case When userID_following = $myID Then 1 Else 0 End ) As followingCount
From t1
Where userID_follower = $myID
    Or userID_following = $myID

答案 2 :(得分:3)

我建议每行返回两行,而不是两列:

SELECT 'follower', COUNT(*) AS count FROM t1 WHERE userID_follower = ?
UNION ALL
SELECT 'following', COUNT(*) FROM t1 WHERE userID_following = ? 

这似乎是一种退化解决方案,但原因是如果对userID_follower和userID_following编制索引,则可以使用索引。如果您尝试将结果分成两列,如其他答案中所示,则无法使用索引并且必须执行表扫描。

与问题相关的其他提示:

  • 在这种情况下使用COUNT(id)没有任何好处。
  • 您应该使用SQL查询参数,而不是在查询中插入$ myID。

答案 3 :(得分:2)

我认为这样的事情应该有效:

select ownerID, count( distinct userID_follow), count(distinct userID_following) from t1 group by ownerID