A
A
Alexander2019-02-03 20:19:51
Flask
Alexander, 2019-02-03 20:19:51

How to group data "by pairs" in MySQL?

There is a table in which there are discussions. The structure is like this:

from_id - от кого
to_id - к кому
p_id - предмет обсуждения
message - сообщения

These are dialogues, i.e. 2 people are talking. Within one p_id there can be messages from one from_id to another to_id and back from to_id to from_id.
for example
from_id | to_id | p_id | message
1 | 2 | 5 | привет
2 | 1 | 5 | и тебе привет

This is an example of a conversation on subject 5. A simple grouping by from_id, to_id, and p_id results in a conversation count of *2, since only "one-way" replicas are counted. The question is how do I pull out all p_id's and their members, i.e. get a list of dialogs?
An important clarification, the same P_id can discuss 1 with 2, 2 with 3 and 1 with 3. and this will be 3 different dialogues

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
MaksPaverov, 2019-02-03
@MaksPaverov

SELECT * FROM msg WHERE from_id=2 OR to_id=2 AND p_id=5;
Something like this

V
Vitsliputsli, 2019-02-03
@Vitsliputsli

For example like this:

SELECT DISTINCT
        p_id,
        CASE WHEN temp.var = 0 THEN from_id ELSE to_id END user_id
    FROM table 
    CROSS JOIN (SELECT 0 var FROM DUAL UNION ALL SELECT 1 var FROM DUAL) temp

The output will be like this:
p_id user_id
5      1
5      2

3
3vi1_0n3, 2019-02-03
@3vi1_0n3

SELECT DISTINCT * FROM
(SELECT from_id as user_id, p_id FROM msg
UNION
SELECT to_id as user_id, p_id FROM msg)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question