Mysql 多列SQL查询与排序

Mysql 多列SQL查询与排序,mysql,sql,Mysql,Sql,我有两个表,邮政编码是一个字段。如果我想获得每个表中的前10名,我使用以下命令 select ZIP, count(*) from tab37 group by ZIP order by count(*) desc limit 10 但是,我还有另外3个表tab38、tab39、tab40,我还想包括这3个表。我如何编写一个查询来执行同样的操作,以获取所有4个表中的前10个邮政编码Union all并将查询括起来 (select ZIP, count(*) from tab37 group b

我有两个表,邮政编码是一个字段。如果我想获得每个表中的前10名,我使用以下命令

select ZIP, count(*) from tab37 group by ZIP order by count(*) desc limit 10

但是,我还有另外3个表tab38、tab39、tab40,我还想包括这3个表。我如何编写一个查询来执行同样的操作,以获取所有4个表中的前10个邮政编码

Union all并将查询括起来

(select ZIP, count(*) from tab37 group by ZIP order by count(*) desc limit 10)
union all
(select ZIP, count(*) from tab38 group by ZIP order by count(*) desc limit 10)
union all
(select ZIP, count(*) from tab39 group by ZIP order by count(*) desc limit 10)
union all
(select ZIP, count(*) from tab40 group by ZIP order by count(*) desc limit 10)
我假设您不关心一个或多个表格中是否存在邮政编码-如果您关心,请适当修改您的问题。

如果您希望表格中的顶部,则在聚合之前先使用union all:

select zip, count(*)
from ((select zip from table37) union all
      (select zip from table38) union all
      (select zip from table39) union all
      (select zip from table40) 
     ) t
group by zip
order by count(*) desc
limit 10;
  

. . 你的问题模棱两可。您想要结果集中的10行还是40行?