Symmetric Pairs

  • + 0 comments

    Explanation: It's not much tricky with few pitfalls to avoid we can solve it easily by two approaches, one by the use of CROSS JOIN and a simple INNER JOIN. The cte here, allocating a unique row number to each row, is to avoid joining a row with itself which may happen here as the rows are coming from the same tables, here cte. The outer most select clause just after the cte definition is to avoid redundancy which may arise due to both the ctes having the values of {x<sub>1</sub>, y<sub>1</sub>} and {x<sub>2</sub>, y<sub>2</sub>} . So, a row which is to be present in the output table which was join by x<sub>1</sub> = y<sub>2</sub> and y<sub>1</sub>} = x<sub>2</sub> can again appear by the y<sub>2</sub> = x<sub>1</sub> and x<sub>2</sub> = y<sub>1</sub>} .

    MySQL Code:

    with cte as
    (
        select
            x,
            y,
            row_number() over (order by x,y) as r
        from functions
    )
    select 
        distinct x, y
    from
        (select 
            case
                when t1.x <= t1.y then t1.x
                else t2.x
            end x,
            case
                when t1.x <= t1.y then t1.y
                else t2.y
            end y
        from 
            cte as t1
            inner join
            cte as t2
            on t1.x = t2.y and t2.x = t1.y and t1.r != t2.r) as tabl
    order by x;