小编典典

MySQL连接表和计数实例

sql

可以说我有下表:

Countries
---------------------------
| ID | Country Name       |
---------------------------
| 1  | Greece             |
| 2  | Italy              |
| 3  | Spain              |
---------------------------

Cities
---------------------------
| ID | City               |
---------------------------
| 1  | Athens             |
| 2  | Patra              |
| 3  | Rome               |
| 4  | Venice             |
---------------------------

Countries & Cities
--------------------
| ID | Cntr | City |
--------------------
| 1  |   1  |   2  |
| 2  |   1  |   1  |
| 3  |   2  |   3  |
--------------------

现在,如何运行MySQL查询,该查询将基于“国家/城市”表返回国家和城市总数?

在示例中返回:

---------------------------
| Cities | Country        |
---------------------------
| 2      | Greece         |
| 1      | Italy          |
---------------------------

阅读 182

收藏
2021-03-08

共1个答案

小编典典

试试看:

SELECT COUNT(cs.City) as Cities, cn.name as Country
FROM countries cn 
INNER JOIN country_city cs ON cs.Cntr = cn.id 
GROUP BY cn.name

输出:

2   | Greece
1   | Italy
2021-03-08