是否可以在同一查询中计算两列 [英] 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:
-
此人正在关注多少用户
how many users this person is following
从t1中选择COUNT(id),其中userID_follower =.$ myID". ."
select COUNT(id) from t1 WHERE userID_follower = ".$myID." ."
有多少用户关注此人
how many users follow this person
从t1 WHERE userID_following =.$ myID."中选择COUNT(id).
select COUNT(id) from t1 WHERE userID_following = ".$myID."
谢谢.
推荐答案
在MySql中,可以在条件上使用SUM()
函数,因为错误条件将等于0
,而真实条件将等于0
. 1
:
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
这篇关于是否可以在同一查询中计算两列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文