A
A
Abdula Magomedov2017-01-26 08:57:31
MySQL
Abdula Magomedov, 2017-01-26 08:57:31

How to link 2 records of the same table?

Hello.
I thought I was pretty good at database theory, but I can't think of one thing. I may have reworked it.
What is the point. There is a certain table of clients. Question: How to connect 2 clients in pairs.
Solutions that come to mind.
1. Create a link table. table(client_1, client2) and create a unique index on two fields, but the table does not prohibit adding 2 records (client_1, client2) and (client_2, client_1), i.e. it turns out for one connection 2 lines were added to me. It turns out that I have to maintain the integrity of the database at the application level. How can I make it impossible to add a second record?
2 (recommended by a friend). Create virtual containers. For each paired connection, create your own container and add both clients to this container. In some cases, this solves the previous problem, but another one appears, how to make sure that a third client is not accidentally added to this container, because. I only need to tie 2 of them. It turns out that here, too, it is necessary to maintain the integrity of the database at the application level.
How do you solve such a problem? Please help, nothing comes to mind.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
d-stream, 2017-01-26
@d-stream

And why confuses (client1, client2) and (client2,client1) ?
For example, if we are talking about trusted persons, then Vasya may be Petya's trustee, and Petya may or may not be Vasya's trustee.
Accordingly, further queries "whom Vasya trusts" and "who has Vasya trusted" - are resolved perfectly, and "who has any relationship with whom" - is resolved with distinct

R
res2001, 2017-01-26
@res2001

Get a field in the table by the value of which you will combine records, let it be the tag field and let this table have a unique id field.
A join query looks like this:

select T1.*, T2.*
from table T1
join table T2 on T2.tag=T1.tag and T2.id <> T1.id

A
Alex, 2017-01-26
@streetflush

Everyone has already written @d-stream correctly here. I’ll
just add the idea to get rid of (client_1, client2) and (client_2, client_1)

select T1.*, T2.*
from table T1
join table T2 on T2.id > T1.id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question