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

san*_*nta 14 mysql

假设我有以下表格结构:

t1
-------------
id // row id
userID_follower // this user is a follows another member
userID_following  // other member that this user 
Run Code Online (Sandbox Code Playgroud)

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

  1. 这个人关注了多少用户

    从t1 WHERE userID_follower =".$ myID"中选择COUNT(id).".

  2. 有多少用户关注此人

    从t1 WHERE userID_following =".$ myID"中选择COUNT(id).

谢谢.

The*_*ter 53

在MySql中,您可以SUM()在条件上使用该函数,因为错误条件将等于0,并且true将等于1:

SELECT SUM(userID_follower = $myID) AS followerCount,
   SUM(userID_following = $myID) AS followingCount
FROM t1
WHERE userID_follower = $myID
   OR userID_following = $myID
Run Code Online (Sandbox Code Playgroud)


Tho*_*mas 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
Run Code Online (Sandbox Code Playgroud)