A
A
Alexey Konovalov2019-05-29 18:30:47
MySQL
Alexey Konovalov, 2019-05-29 18:30:47

How to select dialog ID and interlocutor ID from the same table?

Hello!
I have a table which contains fields:

  • dialog_id - ID of the dialog in which the user is participating
  • user_id - user ID

Both 2 and 3+ users can participate in the dialogue. And for example, when sending a message to the user, I first need to find out in which dialogue to send him a message (well, that is, what is the ID of the dialogue in which we corresponded with him before).
It turns out that I have to select entries in which user_id = 1 or user_id = 2, while these entries have a common dialog_id and the number of interlocutors in the dialog should not exceed 2.
I always come up with one request:
SELECT dialog_id 
FROM members 
WHERE user_id = 1 OR user_id = 2
GROUP BY dialog_id HAVING count(dialog_id) = 2

Logically, this query would work. But Having is useless here, since we specified specific user IDs in the condition. Therefore, if these users are present in other, general, dialogs, then their IDs will be displayed by this request.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kova1ev, 2019-05-29
@kova1ev

This option pops into my head:

SELECT dialog_id FROM members
GROUP BY dialog_id HAVING count(user_id) = 2
AND dialog_id IN (
    SELECT dialog_id 
    FROM members 
    WHERE user_id = 1 OR user_id = 2
    GROUP BY dialog_id HAVING count(user_id) = 2)

that is, we select all dialogs with two users and check which one is in the dialogs with the necessary users

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question