mysql - 根据 2 列选择行

标签 mysql sql select group-by

我并不是最擅长 SQL,但我正在努力实现以下目标:

我有一个包含如下列的表格:

id | cup_type | cup_id | name

我的数据库中有大量记录,它们具有相同的 cup_id 但不同的 cup_types

我真的很想选择具有相同 cup_id 但不同 cup_types 的记录

id | cup_type | cup_id | name
1  | TypeOne  | 12     | NameOne
2  | TypeTwo  | 12     | NameTwo
3  | TypeOne  | 13     | NameThree
4  | TypeTwo  | 13     | NameFour
5  | TypeOne  | 14     | NameFive
6  | TypeOne  | 14     | NameSix

当我运行上述查询时,我会返回以下内容:

id | cup_type | cup_id | name
1  | TypeOne  | 12     | NameOne
2  | TypeTwo  | 12     | NameTwo
3  | TypeOne  | 13     | NameThree
4  | TypeTwo  | 13     | NameFour

我希望我已经解释清楚了,如果需要更清楚的说明,请告诉我。

最佳答案

这个查询就可以了

select * from
yourtable a
join (select cup_id, count(distinct cup_type) nbType
        from yourTable
        group by cup_id) b using(cup_id)
where b.nbType >= 2;
  • 从表格中获取结果集,在其中计算不同的 cup_type
  • cup_id 对结果集进行分组。
  • 保留 cup_id,以便我们可以使用该 ID 加入同一张 table 。
  • 仅返回不同类型数量至少为 2 的类型。

关于mysql - 根据 2 列选择行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29289909/

相关文章:

javascript - 使用 onmouseup 删除选项的选择

php - undefined variable $db_hostname

mysql - 具有不同值的多个表上的 SQL 左连接

mysql - 日期时间与日期和时间 Mysql

php - codeigniter 中的子字符串查询

sql - 如何计算按日期分组的SQLite和SUM这些值的时差?

mysql - SQL查询解决

表名称附近的 C# 语法错误

mysql - 使用条件选择一列作为不同的列名称

c# - 连接到我的数据库时出错(MySQL、C#)