返回下一列中具有不同值的行

  • 本文关键字:一列 返回 sql
  • 更新时间 :
  • 英文 :


我想编写一个返回具有 2 个不同值的行的查询作为示例:

这是我拥有的表 - 表名为Deliveryschedulefruits

ContactId  Fruit
-----------------
45166      apple
45168      apple
45169      apple
45166       orange

结果应该是:

45166      apple
45166      orange

我自己尝试了一些解决方案,但无法得出预期的结果: 这行不通。我觉得应该

select  * 
from MOW_DeliveryScheduleFruits 
where ContactId IN (select a.ContactId 
from MOW_DeliveryScheduleFruits a
join MOW_DeliveryScheduleFruits b On b.ContactId = a.ContactId 
And b.Fruit <> a.Fruit)

请帮助我。我似乎无法解决这个问题。

试试这个

select MOW_DeliveryScheduleFruits.*
from(    
select ContactId 
from MOW_DeliveryScheduleFruits
group by ContactId 
having count(*)>1
) as doubles
inner join MOW_DeliveryScheduleFruits on MOW_DeliveryScheduleFruits.ContactId=doubles.ContactId 
order by MOW_DeliveryScheduleFruits.ContactId, Fruit

子查询返回所需的所有 ID。你可以用这些ID阅读水果。

我认为您的查询有问题,如果您每contactID有超过 2 个水果,它将返回 dublicate。您需要使用distinct.喜欢这个。

select  * from MOW_DeliveryScheduleFruits 
where ContactId IN (
select distinct a.ContactId 
from MOW_DeliveryScheduleFruits a
Join MOW_DeliveryScheduleFruits b
ON b.ContactId = a.ContactId AND b.Fruit <> a.Fruit
)

使用group by比额外的join更有效。

我只会使用exists

select f.*
from fruits f
where exists (select 1
from fruits f2
where f2.contactid = f.contactid and f2.fruit <> f.fruit
);

如果您有一个大表,这可以充分利用(contactid, fruit)上的索引。

最新更新