mysql:两个计数之和(按不同的值)

a0zr77ik  于 2021-06-17  发布在  Mysql
关注(0)|答案(3)|浏览(317)

我的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)次,则a-b-连杆的总和为八(8)。
用mysql公式可以吗?谢谢你的帮助!

hzbexzde

hzbexzde1#

你可以 join 结果是:

select t1.citer as person, t1.citations1 + t2.citations2 as result
from
(
SELECT citer,COUNT(citer) AS citations1 FROM `table` WHERE cited='A' GROUP BY citer ORDER BY citations1 DESC
) t
join
(
SELECT cited,COUNT(cited) AS citations2 FROM `table` WHERE citer='A' GROUP BY cited ORDER BY citations2 DESC
) t2
on t1.citer = t2.cited
x9ybnkn6

x9ybnkn62#

你可以这样写:

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;

这个问题有点棘手。如果你试图使用 join ,您将排除引用链接最多的人仅为“引用人”或仅为“引用人”的可能性。

y1aodyip

y1aodyip3#

我在子查询中使用union,然后是行的和

SELECT other, SUM(citations)
FROM (
   SELECT citer other,COUNT(*) AS citations 
   FROM citations 
   WHERE cited='A'        
   GROUP BY citer 
   UNION
   SELECT cited, COUNT(*)
   FROM citations 
   WHERE citer='A' 
   GROUP BY cited) AS uni
GROUP BY other

相关问题