Is it possible to count two columns in the same query

后端 未结 4 1026
栀梦
栀梦 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题