mysql - 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 |
我怎样才能解决这个问题?
解决方案
您可以使用条件聚合。在 MySQL 中,您可以使用快捷方式SUM(<boolean value>)
来统计真值的数量:
SELECT country, SUM(type = 'Getting inspired') AS `count`
FROM `myTable`
GROUP BY country
ORDER BY `count` DESC
推荐阅读
- elasticsearch - 在映射中设置自定义类型名称
- docker - 如何在 docker-compose 中设置环境变量
- excel - 如何在VBA中将文件名调用到excel公式中
- c# - 从旧 Azure 库(Microsoft.ServiceBus.Messaging 命名空间)中的抽象类继承。找不到合适的方法来覆盖
- android - 如何使用 ionic 3 @ionic-native/http 在本机 HTTP 中传递 FormData?
- r - 无法访问 dbplyr 中的字符串方法
- c# - 有没有办法合并两个具有相同键的对象数组,总结另一个属性的值?
- error-handling - Spring Integration - 如何将错误处理委托给单独的线程
- windows - 如何识别对 DLL 进行了哪些调用?
- reactjs - React material-ui grid:是否可以添加断点?