我正在试图找出如何查询我的表以查看一组user_id是否与conversation_id匹配。
查询1应返回以下结果: user_id 1正在查看是否有任何conversation_id,其中只有user_id = 2和user_id = 1。 (应根据SQL Fiddle示例为每个conversation_id = 1,2,4,5返回一行)
conversation_id
1
2
4
5
查询2应返回以下结果: user_id 1正在查看是否有任何conversation_id与user_id = 2,user_id = 1,和user_id = 4 。 (应返回0行,因为它在SQL Fiddle示例中不存在)
表格设置位于 SQL Fiddle
答案 0 :(得分:1)
您可以使用group by ... having
和相关exists
子查询的组合来获得所需的结果:
-- Query 1:
SELECT
conversation_id
FROM
users_conversations uc
where not exists (
select 1 from users_conversations
where conversation_id = uc.conversation_id
and user_id not in (1,2)
)
group by conversation_id
having count(distinct user_id) = 2;
-- Query 2: same query, only different numbers.
SELECT
conversation_id
FROM
users_conversations uc
where not exists (
select 1 from users_conversations
where conversation_id = uc.conversation_id
and user_id not in (1,2,4))
group by conversation_id
having count(distinct user_id) = 3;
请注意,第一个查询不会返回1,2,4,5
,而是返回2,5
,但在您的示例数据中,1或4都只有user_id 1和2作为参与者(conversation 1
具有{{1} }},1,2,3,4
有conversation 4
)。
答案 1 :(得分:1)
如果我理解正确的话应该是他的。
Q1:
SELECT
CASE
WHEN
count(distinct CASE WHEN user_id in ('1','2') THEN user_id END)>='2'
THEN `conversation_id`
END 'test'
FROM
users_conversations
where 1
group by `conversation_id`
Q2:
SELECT
CASE
WHEN
count(distinct CASE WHEN user_id in ('1','2','4') THEN user_id END)>='3'
THEN `conversation_id`
END 'test'
FROM
users_conversations
where 1
group by `conversation_id`