首页 > 解决方案 > MySQL:两个 COUNT 的总和(按不同的值)

问题描述

我的 MySQL 表保存引用。每行是一个引用,如下所示:

A = citer, B = cited(即 A 引 B)。

我知道如何获取 (1) 谁最常引用 A,以及 (2) 谁最常引用 A:

/* (1) who cited A most often? */
SELECT citer,COUNT(citer) AS citations1 FROM `table` WHERE cited='A' GROUP BY citer ORDER BY citations1 DESC

/* (2) whom did A cite most often? */
SELECT cited,COUNT(cited) AS citations2 FROM `table` WHERE citer='A' GROUP BY cited ORDER BY citations2 DESC

现在我想要得到这两个统计数据的总和(citations1+ citations2),这样我就知道谁与 A 的总引用链接最多。

示例:如果 B 引用 A 五 (5) 次,A 引用 B 三 (3) 次,则 AB 链接的总和为八 (8)。

使用 MySQL 公式可以实现吗?谢谢您的帮助!

标签: mysqlsql

解决方案


你可以这样写:

select person, (sum(citers) + sum(citeds)) as total
from ((select citer as person, count(*) as citers, 0 as citeds
       from citations
       where cited = 'A'
       group by citer
      ) union all
      (select cited, 0, count(*) as citeds
       from citations
       where citer = 'A'
       group by cited
      )
     ) c
group by person
order by total desc;

这个问题有点棘手。如果您尝试使用 a join,您将排除具有最多引用链接的人只是“引用者”或“被引用”的可能性。


推荐阅读