是否有可能在同一个查询来算两列

问题描述:

比方说,我有以下表结构:是否有可能在同一个查询来算两列

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

是否有可能运行一个查询到以下两者结合:

  1. 有多少用户这个人以下从T1 WHERE userID_follower =

    SELECT COUNT(ID) “$身份识别码。” 。 “

  2. 多少用户遵循从T1这个人

    SELECT COUNT(ID),其中userID_following =” $身份识别码。”

感谢。

在MySQL中,你可以使用SUM()功能上的条件,因为一个错误的条件将等于0,和一个真正的人会等于1

SELECT SUM(userID_follower = $myID) AS followerCount, 
    SUM(userID_following = $myID) AS followingCount 
FROM t1 
WHERE userID_follower = $myID 
    OR userID_following = $myID 
+1

我的天啊。这给了子集数量很多的优点,而不需要通过where子句来筛选整个选择。非常感谢! – C4u 2015-12-01 15:03:24

+0

你为什么需要where子句? – 2017-09-07 19:11:58

+0

@IstiaqueAhmed列应该被索引。不需要进行全表扫描。 – 2017-09-08 08:05:56

我认为这样的事情应该可以工作:

select ownerID, count(distinct userID_follow), count(distinct userID_following) from t1 group by ownerID 
+0

哦,你是对的,但我如何得到的计数值?我应该如AS cont1和AS cnt2? – santa 2011-02-27 13:34:14

+0

是的,'count(distinct userID_follow)as cnt1' should be working。 – SiggyF 2011-02-27 17:30:46

我建议返回两列一个计数每一行,而不是两列:

SELECT 'follower', COUNT(*) AS count FROM t1 WHERE userID_follower = ? 
UNION ALL 
SELECT 'following', COUNT(*) FROM t1 WHERE userID_following = ? 

这可能看起来是简并的解决方案,但其原因是,如果userID_follower和userID_following是指数编辑,这可以利用指标。如果您尝试按照其他答案中所示的方式将结果显示在两列中,则无法使用索引并必须执行表扫描。

其他提示,相切的问题:

  • 没有什么优势,在这种情况下使用COUNT(ID)。
  • 您应该使用SQL查询参数,而不是将$ myID插入到查询中。
+0

'不能使用索引并且必须执行表扫描',这是不正确的。请参阅http://dev.mysql.com/doc/refman/5.0/en/index-merge-optimization。html – 2011-03-03 22:08:03

+0

@Scrum:Aha,你说得对,如果我用更多的随机数据测试几千行,MySQL确实会使用索引并执行联合合并。我测试过的行数太少,或者没有足够的随机分布。 – 2011-03-03 22:54:17

更霍伊尔(ISO)的解决办法是使用CASE表达式:

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 
+0

没有事件需要CASE,因为我的列是int。谢谢! – Dan 2013-09-13 20:57:38