How to return rows that have the same column values in MySql(如何在MySql中返回具有相同列值的行)
问题描述
让我们考虑下表-
ID Score
1 95
2 100
3 88
4 100
5 73
我是一个完全的 SQL 菜鸟,但如何返回具有 ID 2 和 4 的分数?所以它应该返回 100,因为它同时出现在 ID 2 和 4
I am a total SQL noob but how do I return the Scores featuring both IDs 2 and 4? So it should return 100 since its featured in both ID 2 and 4
推荐答案
这是一个sets-within-sets"查询示例.我建议使用 have
子句进行聚合,因为这是最灵活的方法.
This is an example of a "sets-within-sets" query. I recommend aggregation with the having
clause, because it is the most flexible approach.
select score
from t
group by score
having sum(id = 2) > 0 and -- has id = 2
sum(id = 4) > 0 -- has id = 4
这是按分数聚合的.然后 have
子句的第一部分 (sum(id = 2)
) 计算每个分数有多少个2".第二个是计算有多少个4".仅返回具有2"和4"的分数.
What this is doing is aggregating by score. Then the first part of the having
clause (sum(id = 2)
) is counting up how many "2"s there are per score. The second is counting up how many "4"s. Only scores that have at a "2" and "4" are returned.
这篇关于如何在MySql中返回具有相同列值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在MySql中返回具有相同列值的行


- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- SQL 临时表问题 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 更改自动增量起始编号? 2021-01-01