mysql 条件相同id不同,MySQL:检索ID,其中恰好2行共享相同的ID但具有不同的用户ID...

I have a MySQL table that associates a user to a conversation that looks like the following image or sqlfiddle:

As you can see, user 1000001 and user 1000002 both belong to 2 conversations - 10 and 20.

What I need to do is retrieve the conversation_id where only users 1000001 and user 1000002 are associated with it. The correct conversation_id that would be pulled is 10.

As you can see with conversation_id 20, a 3rd user is associated with it - 1000003 - so I don't want to pull that conversation_id, even though users 1000001 and 1000002 are associated with it.

Also note that the scenario can't happen when only one user_id is associated with a conversation_id.

Thank you so much for your help!

解决方案

Here is a performant approach, using no subqueries at all. You can simply filter out results in Having clause, using conditional aggregation:

SELECT

conversation_id

FROM assoc_user__conversation

GROUP BY conversation_id

HAVING

-- all the rows to exists only for 1000001 or 1000002 only

SUM(user_id IN (1000001, 1000002)) = COUNT(*)

Result

| conversation_id |

| --------------- |

| 10 |

Another variation of conditional aggregation possible is:

SELECT

conversation_id

FROM assoc_user__conversation

GROUP BY conversation_id

HAVING

-- atleast one row for 1000001 to exists

SUM(user_id = 1000001) AND

-- atleast one row for 1000002 to exists

SUM(user_id = 1000002) AND

-- no row to exist for other user_id values

NOT SUM(user_id NOT IN (1000001, 1000002))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值