获得两个用户之间的相互订阅

时间:2012-02-13 09:07:06

标签: mysql sql

我有一张表如下

id comm_id user_id ..

这将用户订阅存储到社区。现在我想查询这个表,以便只获取那些在2个用户之间相互作用的订阅(比如user_id:2和9)

给我sql查询 tablename:db_community_subscribers id,community_id,user_id

"20"      1         "2"
"28",  NULL         "2"
"31"   NULL,        "2"
"43",   4           "2"
"47     1             9
"57",   NULL,       "2"
"59",   "12",      "9"
"60     14          2
"62",  NULL         2

这些是用户2和9的订阅

我想只选择1和12,因为这些是常见的订阅

4 个答案:

答案 0 :(得分:3)

试试这个:

我认为现在可行了:

SELECT Comm_ID
FROM tableNAme
WHERE  user_id IN (2,9)
GROUP BY Comm_ID
HAVING COUNT(Comm_ID) > 1

SELECT DISTINCT d.Comm_ID
FROM
    (SELECT Comm_ID
    FROM tableNAme
    WHERE user_id in (1,2)) d
GROUP BY d.Comm_ID
HAVING COUNT(d.Comm_ID) > 1

答案 1 :(得分:1)

尝试以下

  SELECT group_concat(distinct comm_id)
  FROM table 
  WHERE user_id in(2, 9)
  group by user_id  having count(id) >1

OR:

  SELECT distinct comm_id
  FROM table 
  WHERE user_id in(2, 9)
  group by user_id  having count(id) >1

请做必要的更改如果您想要其他任何内容,请告诉我。

答案 2 :(得分:1)

尝试:

select comm_id, group_concat(id) as subscription_ids
from subscriptions
where user_id in (2,9)
group by comm_id
having count(distinct user_id)=2

答案 3 :(得分:1)

你试过一个简单的JOIN吗?

SELECT t1.`community_id`
FROM `tablename` t1
LEFT JOIN tablename t2 ON (t1.`community_id` = t2.`community_id`)
WHERE t1.`user_id` = 2
    AND t2.`user_id` = 9

对于每个user_id 2社区,应该找到匹配的用户9社区。