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:
how many users this person is following
select COUNT(id) from t1 WHERE userID_follower = ".$myID." ."
how many users follow this person
select COUNT(id) from t1 WHERE userID_following = ".$myID."
Thanks.
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
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
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With