简体   繁体   English

Select 唯一的 field1 有 >1 个不同的 field2 实例与之关联?

[英]Select unique field1 that has >1 distinct instances of field2 associated with it?

How can I query for the distinct field1 instances that have multiple distinct corresponding field2 values?如何查询具有多个不同对应 field2 值的不同 field1 实例?

field1字段1 field2字段2
a一个 apple苹果
b b grape葡萄
c c banana香蕉
b b orange
a一个 apple苹果

In this example I want to return "b", since there are at least 2 distinct values (grape and orange) for field2 that correspond to it.在此示例中,我想返回“b”,因为 field2 至少有 2 个不同的值(葡萄和橙色)与之对应。 I don't wan't "a" since there is only 1 unique field2 value that corresponds, "apple".我不想“a”,因为只有 1 个唯一的 field2 值对应,“apple”。

I have tried我努力了

with all_unique_combos as (
select distinct field1, field2
from table
)

select field1
from all_unique_combos
group by field1
having count(field2) > 1

I actually think this is right and would give me what I need.我实际上认为这是正确的,并且会给我我需要的东西。 But at the moment it's returning 0 rows so I kinda need a sanity check.但目前它返回 0 行,所以我有点需要进行健全性检查。 Thanks for any input either way.感谢您的任何输入。

You can use aggregation:您可以使用聚合:

select field1
from t
group by field1
having min(field2) <> max(field2);

A straight-forward approach uses group by and having :直接的方法使用group byhaving

select field1
from mytable
group by field1
having min(field2) <> max(field2)

Using COUNT(DISTINCT...) :使用COUNT(DISTINCT...)

select field1
from tab
group by field1
having count(disitnct field2) > 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 MYSQL仅在field1或field2不等于文本的情况下选择field1,field2 - MYSQL select field1, field2 only where field1 or field2 does not equal text Oracle PL / SQL:从已分区表的两个中间分区中选择DISTINCT FIELD1,FIELD2 - Oracle PL/SQL: SELECT DISTINCT FIELD1, FIELD2 FROM TWO ADIACENT PARTITIONS OF A PARTITIONED TABLE mysql相关子查询:选择field1,其中max(field2) - mysql correlated subquery : select field1 where max(field2) (MySQL)OrderBy Field1 = 3,Field2 - (MySQL) OrderBy Field1=3, Field2 复制field2时更新field1 - Update field1 when field2 is duplicated 参数化查询中的(?,?...?)或(@ field1,@ field2 ... @ fieldn)? - (?,?…?) or (@field1,@field2…@fieldn) in parmeterized queries? Mysql在哪里查询…选择* where field1 + field2 + field3 &lt;=字段4 - Mysql where query… select * where field1 +field2 + field3 <= field 4 使用“SELECT Field1,Field2,Field3 ......”代替“SELECT * ...”可以获得性能提升吗? - Is there a performance gain achieved by using “SELECT Field1, Field2, Field3 …” instead of “SELECT * …” 从表中选择*或从表中选择id,field1,field2,field3 - 最佳实践? - Select * from table OR select id,field1, field2, field3 from table - best practice? Oracle查询,其中field1 = field2和field2 = field1 - Oracle query where field1=field2 and field2=field1
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM