首页 > 解决方案 > SQL 选择所有字段,然后覆盖值

问题描述

我有个问题。在我的数据库中,我有以下表结构:

| id | name  | country     | type             |   |
|----|-------|-------------|------------------|---|
| 1  | test1 | UK          | Getting inspired |   |
| 2  | test2 | Netherlands | Overwriting      |   |
| 3  | test3 | UK          | Getting inspired |   |

现在我想选择具有以下类型的国家和计数:Getting inspired。为此,我进行了以下查询:

SELECT `country`, COUNT(`country`) AS `count` 
FROM `myTable` 
WHERE `type`='Getting inspired') 
GROUP BY `country` 
ORDER BY `count` DESC

这导致以下结果:

| country     | count     |
|-------------|-----------|
| UK          | 2         |

但我也想Netherlands用count的国家:0。我尝试了以下方法:

SELECT `country`, '0' AS count 
FROM `myTable` 
UNION 
SELECT `country`, COUNT(`country`) AS `count` 
FROM `myTable` 
WHERE (`type`='Getting inspired') 
GROUP BY `country` 
ORDER BY `count` DESC

在这里,我尝试首先选择所有国家并为其赋值0,然后尝试覆盖值大于0. 但是,这会导致重复的国家/地区:

| country     | count     |
|-------------|-----------|
| UK          | 2         |
| Netherlands          | 0         |
| UK| 0         |

我想要得到的结果是这样的:

| country     | count     |
|-------------|-----------|
| UK          | 2         |
| Netherlands          | 0         |

我怎样才能解决这个问题?

标签: mysqlsqldatabase

解决方案


您可以使用条件聚合。在 MySQL 中,您可以使用快捷方式SUM(<boolean value>)来统计真值的数量:

SELECT country, SUM(type = 'Getting inspired') AS `count`
FROM `myTable`
GROUP BY country
ORDER BY `count` DESC

推荐阅读