在表中找到两个具有相同值的记录

时间:2019-07-02 12:29:18

标签: mysql

我有一张桌子b_im_message。它具有列idchat_iduser_id。我无法创建查询,因此在“ user_id”列中有3或4个值,在chat_id列中有两个条目。很难描述。我将举一个例子。

初始表格视图

mysql> select id, chat_id, user_id from b_im_relation;
+----+---------+---------+
| id | chat_id | user_id |
+----+---------+---------+
| 11 |       6 |       1 |
| 12 |       6 |       3 |
| 13 |       7 |       1 |
| 14 |       7 |       4 |
| 16 |       8 |       1 |
| 15 |       8 |       3 |
| 18 |       9 |       1 |
| 17 |       9 |       4 |
| 19 |      10 |       3 |
| 20 |      11 |       3 |
| 21 |      11 |       4 |
+----+---------+---------+
11 rows in set (0.00 sec)

选择值为3或4以及任意“ chat_id”的行

mysql> SELECT id, chat_id, user_id 
       FROM b_im_relation 
       WHERE user_id IN (3,4) and  
             EXISTS(SELECT id, chat_id, user_id 
                    FROM b_im_relation t1 
                    WHERE EXISTS (SELECT 1 
                                  FROM b_im_relation t2 
                                  WHERE t1.chat_id=t2.chat_id and 
                                  t1.id<>t2.id));
+----+---------+---------+
| id | chat_id | user_id |
+----+---------+---------+
| 12 |       6 |       3 |
| 15 |       8 |       3 |
| 19 |      10 |       3 |
| 20 |      11 |       3 |
| 14 |       7 |       4 |
| 17 |       9 |       4 |
| 21 |      11 |       4 |
+----+---------+---------+
7 rows in set (0.00 sec)

选定对“ chat_id”

mysql> SELECT id, chat_id, user_id 
       FROM b_im_relation t1 
       WHERE EXISTS (SELECT 1 FROM b_im_relation t2 
                     WHERE t1.chat_id=t2.chat_id and 
                              t1.id<>t2.id) and 
             EXISTS (SELECT id, chat_id, user_id 
                     FROM b_im_relation 
                     WHERE user_id in (3,4));
+----+---------+---------+
| id | chat_id | user_id |
+----+---------+---------+
| 11 |       6 |       1 |
| 12 |       6 |       3 |
| 13 |       7 |       1 |
| 14 |       7 |       4 |
| 16 |       8 |       1 |
| 15 |       8 |       3 |
| 18 |       9 |       1 |
| 17 |       9 |       4 |
| 20 |      11 |       3 |
| 21 |      11 |       4 |
+----+---------+---------+

我需要这个:

+----+---------+---------+
| id | chat_id | user_id |
+----+---------+---------+
| 20 |      11 |       3 |
| 21 |      11 |       4 |
+----+---------+---------+

任何值“ id”,任何相同的值“ cat_id”以及“ user_id”中的“ 3”或“ 4”

2 个答案:

答案 0 :(得分:0)

找到具有多个记录的所有用户/聊天组合,然后加入以获得所有此类记录:

select id, chat_id, user_id
from (
    select chat_id, user_id
    from b_im_relation
    where user_id in (3,4)
    group by chat_id, user_id
    having count(*) > 1
) multiple_chats
natural join b_im_relation

答案 1 :(得分:0)

如果您要使用chat_id的第3和第4个在其中的user_id

select i.*
from b_im_relation i inner join (
    select chat_id
    from b_im_relation
    where user_id in (3,4)
    group by chat_id
    having count(distinct user_id) = 2
) t on t.chat_id = i.chat_id

如果您想让chat_id的第3和第4个仅在其中{}:

user_id