计算(几个)MySQL查询的重叠结果

时间:2014-12-17 12:28:35

标签: mysql select count resultset

我想在MySQL数据库上运行3个不同的SELECT查询:

数据库包含以下条目:

Rio      SouthAmerica
Rio      startsWithR
Rio      endsWithO
Rome     Europe
Rome     startsWithR
Rome     endsWithE
Curitiba SouthAmerica
Curitiba startsWithC
Curitiba endsWithA
Recife   SouthAmerica
Recife   startsWithR
Recife   endsWithE

现在我执行以下查询

SELECT city FROM db.tab WHERE tag="SouthAmerica"
/*Result: Rio, Curitiba, Recife */
SELECT city FROM db.tab WHERE tag="startsWithR"
/*Result: Rio, Recife, Rome */
SELECT city FROM db.tab WHERE tag="endsWithO"
/*Result: Rio */

现在我想算一下,这些问题导致城市返回的频率。我可以通过迭代结果来做到这一点,但我确信有更好的方法。我可以用一个查询来完成吗?或者我需要嵌套查询?我想得到结果:

Rio      3
Recife   2
Curitiba 1
Rome     1

1 个答案:

答案 0 :(得分:1)

使用union all和聚合:

SELECT city, count(*)
FROM ((SELECT city FROM db.tab WHERE tag="SouthAmerica"
      ) UNION ALL
      (SELECT city FROM db.tab WHERE tag="startsWithR"
      ) UNION ALL
      (SELECT city FROM db.tab WHERE tag="endsWithO"
      )
     ) c
GROUP BY city;

实际上,我注意到所有三个子查询都来自同一个表。所以,只需使用条件聚合:

SELECT city, sum(tag in ('SouthAmerica', 'startsWithR', 'endsWithO'))
FROM db.tab
GROUP BY city;

或者

SELECT city, count(*)
FROM db.tab
WHERE tag in ('SouthAmerica', 'startsWithR', 'endsWithO')
GROUP BY city;