SQL:比较来自不同表的两个计数

时间:2016-02-05 02:55:46

标签: mysql sql

我有3个表,其中包含世界上每个国家及其令牌

NAME              CODE
Afghanistan       AFG
Albania           AL
Algeria           DZ
American Samoa    AMSA
Andorra           AND
Angola            ANG
Anguilla          AXA
(...)

以及这些国家所有湖泊和另一座山脉的表格。

LAKE                 CODE
Bodensee             A
Neusiedlersee        A
Lake Prespa          AL
Lake Ohrid           AL
Lake Skutari         AL
Lake Eyre            AUS
Lake Jindabyne       AUS
Lake Hume            AUS
Lake Eucumbene       AUS
Lake Hume            AUS
Lake Burley Griffin  AUS
(...)

MOUNTAIN             CODE
Hochgolling          A
Hochgolling          A
Zugspitze            A
Grossglockner        A
Jezerce              AL
Korab                AL
Uluru                AUS
Mt. Kosciuszko       AUS
Mt. Bogong           AUS
Musala               BG
Illampu              BOL
Sajama               BOL
Licancabur           BOL
(...)

我现在必须向那些山脉数量少于湖泊的国家展示。我现在试了好几个小时但却找不到解决这个问题的方法。 我试图将3张桌子加在一起 ​​- 但我无法弄清楚接下来要做什么。我确定我必须使用嵌套的SQL命令。

这是我尝试计算每个国家的湖泊和山脉

SELECT Country.name, count(Geo_lake.code), count(Geo_mountain.code) 
From Country 
INNER JOIN Geo_lake On (Country.code = geo_lake.code)
INNER JOIn Geo_mountain On (Country.code = geo_mountain.code) 
Group by Country.name;

但不知何故,两个列计数(Geo_lake.country)和计数(Geo_mountain.country)似乎都具有相同的值,我不确切知道为什么。

1 个答案:

答案 0 :(得分:1)

首先获得每个人的总和:

# 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

然后将结果连接在一起并选择一个国家的山脉总和小于湖泊数量的所有行:

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