Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to count two columns in the same query

Tags:

mysql

Let's say I have the following table structure:

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

Is it possible to run a single query to combine both of the following:

  1. how many users this person is following

    select COUNT(id) from t1 WHERE userID_follower = ".$myID." ."

  2. how many users follow this person

    select COUNT(id) from t1 WHERE userID_following = ".$myID."

Thanks.

like image 254
santa Avatar asked Feb 27 '11 13:02

santa


3 Answers

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
like image 110
The Scrum Meister Avatar answered Sep 25 '22 20:09

The Scrum Meister


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
like image 21
Thomas Avatar answered Sep 22 '22 20:09

Thomas


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.
like image 21
Bill Karwin Avatar answered Sep 25 '22 20:09

Bill Karwin