R
R
Roman Sokharev2014-04-24 17:17:35
SQL
Roman Sokharev, 2014-04-24 17:17:35

How to choose a unique combination of SQL fields?

Given:
Relationship table. Where there are fields user1, user2, relation
Task:
Select only unique combinations of these fields.
For example
, us1 / us2 / rel
Vasya / Petya / brothers - falls into the selection
Vasya / Petya / friends - does not fit, such a combination was higher in the line
Petya / Vasya / enemies - fits - there was no such combination
At the same time, I do not need all possible combinations these fields. I need only those that are written in the database, but they should not be repeated.
Just tell me where to dig - I'll handle it myself.
Thank you.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Eugene, 2014-04-24
@greabock

SELECT * FROM rel GROUP BY CONCAT(us1, '|', us2, '|', rel)

E
Eugene, 2014-04-24
@Nc_Soft

Temporary table with unique indexes + INSERT IGNORE

U
UnholyFather, 2014-04-24
@UnholyFather

with t as
(
select 'Vasya' usr1, 'PETER' usr2, 'FRIENDSHIP' rel from dual
union all
select 'Vasya' usr1, 'PETIA' usr2, 'SERVICE' rel from dual
union all
select 'PETYA' usr1, 'Vasya ' usr2, 'LOVE' rel from dual
union all
select 'SEREZHA' usr1, 'Vasya' usr2, 'sympathy' rel from dual
)
select usr1, usr2, rel
from
(select usr1,
usr2,
rel,
row_number() over(partition by usr1 || usr2 order by usr1 || usr2) rn
from t)
where rn = 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question