按两个表分组

时间:2014-09-07 19:56:30

标签: mysql group-by

我有两个具有相同架构的表。我想得到两张桌子中所有姓氏的人数,并且发现我可以这样做:

SELECT surname, count(*) AS cnt
FROM
(
    SELECT surname
    FROM people.NorthKorea
    UNION ALL
    SELECT surname
    FROM peopleGlobal.NorthKorea
) AS t
GROUP BY surname
ORDER BY cnt DESC

这适用于小型表,但我有多达2.5亿行的表,所以想知道是否有更有效的方法可以做到这一点?比如将COUNT的结果从一个表插入表中,然后在第二个表上更新/插入(REPLACE?)COUNT的结果。

N.B。我实际上想在另一个表中的两个表上存储COUNT的结果。

1 个答案:

答案 0 :(得分:1)

姓氏列上的索引应该有很多帮助。我会尝试使用这个查询,如果有更多行而不是姓,我希望它运行得更快:

SELECT surname, SUM(cnt)
FROM
(
   SELECT surname, COUNT(*) as cnt
   FROM people.NorthKorea
   GROUP BY surname
   UNION ALL
   SELECT surname, COUNT(*) as cnt
   FROM peopleGlobal.NorthKorea
   GROUP BY surname
)
GROUP BY surname
ORDER BY cnt DESC