我的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公式可以吗?谢谢您的帮助!
答案 0 :(得分:1)
您可以这样写:
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
,则将排除引用链接最多的人只是“公民”或“被引用”的可能性。
答案 1 :(得分:0)
您可以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
答案 2 :(得分:0)
我在子查询中使用了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