Is it possible to count two columns in the same query

后端 未结 4 1009
栀梦
栀梦 2020-12-05 18:58

Let\'s say I have the following table structure:

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


        
相关标签:
4条回答
  • 2020-12-05 19:35

    The more Hoyle(ISO) solution would be using a Case expression:

    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
    
    0 讨论(0)
  • 2020-12-05 19:35

    I recommend returning two rows with one count on each row, instead of two columns:

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

    This may seem like a degenerate solution, but the reason is that if userID_follower and userID_following are indexed, this can utilize the indexes. If you try to get the results in two columns as shown in the other answers, the can't use the indexes and has to do a table-scan.

    Other tips that are tangential to the question:

    • There's no advantage to using COUNT(id) in this case.
    • You should use SQL query parameters instead of interpolating $myID into your query.
    0 讨论(0)
  • 2020-12-05 19:48

    In MySql, You can use the SUM() function over a condition, since a false condition will equal to 0, and a true one will equal to 1:

    SELECT SUM(userID_follower = $myID) AS followerCount,
       SUM(userID_following = $myID) AS followingCount
    FROM t1
    WHERE userID_follower = $myID
       OR userID_following = $myID
    
    0 讨论(0)
  • 2020-12-05 19:48

    I think something like this should work:

    select ownerID, count( distinct userID_follow), count(distinct userID_following) from t1 group by ownerID
    
    0 讨论(0)
提交回复
热议问题