简体   繁体   中英

Insert unique pair values from another table with select/join

So I have a table which looks something like this:

[sides]
--------------------
left | right
A    | B
A    | C
A    | D
B    | A
--------------------

Note that the first and the last rows are the same value pairs. What I need to do is insert all unique pairs into another table, which would look like this after executed on the above table:

[pairs]
------------------
val1  |  val2
A     |  B
A     |  C
A     |  D
------------------

So far I have this code:

INSERT INTO pairs (val1, val2)
SELECT DISTINCT s1.left, s1.right
FROM sides s1;

As you can see it's only copies the pairs but not a solution for my problem.

Use least() and greatest() :

INSERT INTO pairs(val1, val2)
    SELECT DISTINCT least(s1.left, s1.right), greatest(s1.left, s1.right)
    FROM sides s1;

EDIT:

The above should work (you can test the select separately). You can also do it this way:

INSERT INTO pairs(val1, val2)
    SELECT s1.left, s1.right
    FROM sides s1
    WHERE s1.left < s1.right
    union all
    SELECT s1.left, s1.right
    FROM sides s1
    WHERE s1.left > s1.right and
          not exists (select 1
                      from sides s2
                      where s1.left = s2.right and s1.right = s2.left
                     );

This version can take advantage of an index on sides(left, right) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM