我已经阅读了很多SQL
次查询并尝试了这些查询,但没有成功做我想要的事情。我想要一个SQL
查询,它接受参数随机成员ID,如果他们有一个共同的对话则返回:
SELECT
conversation_id
FROM conversation_mapping
WHERE user_id IN ('1902616933097029', '1112126462227347', '26544849', '13587745')
GROUP BY conversation_id
HAVING COUNT(conversation_id) <> 1
这给了我这个结果:
38
39
结果并不好,因为在ids&#39; 1902616933097029&#39; 1112126462227347&#39; 26544849&#39;,&#39; 13587745根本没有两个共同的谈话。
我的表
---------------------------------------
| user_id | conversation_id |
---------------------------------------
|'1112126462227347'| 38 |
|"1112126462227347"| 39 |
|"13587445" | 39 |
|"1902616933097029"| 38 |
|"1902616933097029"| 39 |
|"26544849" | 38 |
|"26544849" | 39 |
|"8541245" | 38 |
---------------------------------------
IN
语句的问题在于它找到了id1或id2或id3,并且没有选择具有相同会话ID的id1 AND id2 AND id3
答案 0 :(得分:1)
如果我理解正确,您希望与所有共有的ID进行对话。如果是,请使用having
子句:
SELECT conversation_id
FROM conversation_mapping
WHERE user_id IN ('1902616933097029', '1112126462227347', '26544849', '13587745')
GROUP BY conversation_id
HAVING COUNT(DISTINCT user_id) = 4;
“4”是IN
列表中的用户数。
答案 1 :(得分:0)
在表格中,您有&#34; 13587 4 45&#34;,但搜索13587 7 45
检查&#34;中的值&#34;条件并且这样做
SELECT
conversation_id
FROM conversation_mapping
WHERE user_id IN ('1902616933097029', '1112126462227347', '26544849', '13587445')
GROUP BY conversation_id
HAVING COUNT(conversation_id) = 4;