我并不是最擅长 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/