Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql Select reciprocal pairs of records, without duplicates

Tags:

select

mysql

I have a table with two columns:

  1. person_id
  2. person_id with whom 1st field id is in cooperation

I need to select all cooperation pairs, it is easy but in what is the problem: table have data like: 987 - 102, 103 - 104, 104 - 103, 21 - 102. As the result with such data i should have 3 cooperation pairs 987 - 102, 103-104, 21-102, as you see 103 - 104 and 104 - 103 records have the same logic, how can I avoid duplicating of them. Any idea?

Thanks, and best regards. Anton.

like image 845
Anton Sementsov Avatar asked Jul 02 '12 17:07

Anton Sementsov


People also ask

How do I find non duplicate records in MySQL?

The go to solution for removing duplicate rows from your result sets is to include the distinct keyword in your select statement. It tells the query engine to remove duplicates to produce a result set in which every row is unique.

How do I ignore duplicate records in SQL while selecting query?

If you want the query to return only unique rows, use the keyword DISTINCT after SELECT . DISTINCT can be used to fetch unique rows from one or more columns. You need to list the columns after the DISTINCT keyword.

How to INSERT duplicate records in MySQL?

The Insert on Duplicate Key Update statement is the extension of the INSERT statement in MySQL. When we specify the ON DUPLICATE KEY UPDATE clause in a SQL statement and a row would cause duplicate error value in a UNIQUE or PRIMARY KEY index column, then updation of the existing row occurs.


1 Answers

You could use MySQL's LEAST() and GREATEST() functions, together with DISTINCT:

SELECT DISTINCT LEAST(a, b), GREATEST(a, b) FROM mytable
like image 194
eggyal Avatar answered Oct 05 '22 21:10

eggyal