Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

SQL:comparando duas contagens de tabelas diferentes


Comece obtendo as somas para cada um individualmente:
# Sum of lakes
SELECT code, count(*) AS sum FROM lakes GROUP BY code

# Sum of mountains
SELECT code, count(*) AS sum FROM mountains GROUP BY code

Em seguida, junte os resultados e selecione todas as linhas em que a soma das montanhas de um país é menor que o número de lagos:
SELECT l.code AS code, l.sum AS lake_count, m.sum AS mountain_count
FROM
(SELECT code, count(*) AS sum FROM lakes GROUP BY code) AS l JOIN
(SELECT code, count(*) AS sum FROM mountains GROUP BY code) AS m
ON l.code = m.code
WHERE m.sum < l.sum