MySQL:检索ID,其中x个与之关联的user_id数

时间:2018-11-04 14:25:20

标签: mysql

非常感谢您的帮助。

我有一个类似于以下数据库小提琴的MySQL表:

https://www.db-fiddle.com/f/xa2Dt9cAPhiMfHcEv8Lifo/0

我需要做的是检索session_id,在其中可以指定与之关联的user_id,并检索与这些user_id完全关联的session_id。

第一个示例:说我想在只有用户1000001和1000002与之关联的情况下获取session_id。将被拉出的正确的session_id是10。

第二个示例:说我想获取仅与用户1000001、1000002和1000003相关联的session_id。将被拉出的正确的session_id是20。

...等等。

还请注意,只有一个user_id与一个session_id相关联时,这种情况就不会发生。

我在这里发布了我的第一个问题,但是后来意识到,我需要能够拉出一个session_id,其中2个或更多(最多16个)指定的user_id与之相关:MySQL: Retrieving ID where exactly 2 rows share the same ID but have different userIDs

我收到的答案之一是,可以通过在IN子句中指定user_id,然后将用户总数放入COUNT(DISTINCT user_id)子句,将其用于2个或更多user_id。但是,这似乎是最慢的答案性能,并且仅在有可能使用user_id_2键(包含session_id和user_id)时才使用EXPLAIN中的session_id键。

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(*) AND 
  -- number of unique user_id is 2
  COUNT(DISTINCT user_id) = 2

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table 
( id SERIAL PRIMARY KEY
, user_id int  NOT NULL
, conversation_id int NOT NULL
, UNIQUE(user_id,conversation_id)
, INDEX(conversation_id,user_id)  
);

INSERT INTO my_table (id, user_id, conversation_id) VALUES
(1, 1, 10),
(2, 2, 10),
(3, 1, 20),
(4, 2, 20),
(5, 3, 20),
(6, 1, 30),
(7, 2, 30),
(8, 3, 30),
(9, 4, 30);

SELECT x.conversation_id
  FROM my_table x
  LEFT
  JOIN my_table y
    ON y.conversation_id = x.conversation_id
   AND y.user_id NOT IN(1,2)
 WHERE x.user_id IN (1,2)
   AND y.id IS NULL
 GROUP
    BY x.conversation_id
HAVING COUNT(*) = 2;
+-----------------+
| conversation_id |
+-----------------+
|              10 |
+-----------------+