前10名-多个表(联合)-SQL

时间:2018-08-13 11:48:55

标签: sql union limit

我想在数据库中使用多个表来列出最近的十大姓氏

对于1张桌子:

SELECT n.prenomsNouveauNe, COUNT(*)
FROM <database>.naissance n
GROUP BY n.prenomsNouveauNe
ORDER BY COUNT(*) DESC
LIMIT 10

对于多个表:

(
 SELECT
  n.prenomNouveauNe, COUNT(*)
  FROM
   <database>.naissance n
   group by n.prenomsNouveauNe
)
UNION ALL
(
 SELECT
  d.prenomDefunt, count(*)
  FROM
   <database>.deces d
   group by d.prenomDefunt
)

但是我无法进入前10名...

1 个答案:

答案 0 :(得分:2)

select theName, count(*) as cnt from
(
 SELECT
  n.prenomNouveauNe as theName
  FROM
   genearmor.naissance n
UNION ALL
 SELECT
  d.prenomDefunt as theName
  FROM
   <database>.deces d
) tmp
group by theName
order by count(*) desc
limit 10;