Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

mysql - Is it possible to count two columns in the same query

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...