Search code examples
sqlmysqljoin

Simply join 2 tables without condition and cross join, MySQL


table 1:

value
a
b

table 2:

value
c
d
e

I need to get this result:

value value
a c
b d
NULL e

So, it's like Simple join, when row from 1st table matches corresponding(by order) row in 2nd table without any condition.

As a kind of workaround, I thought out this one:

SELECT value, "table1" AS src FROM t1
UNION ALL
SELECT value, "table2" AS src FROM t2

which gives:

value src
a table1
b table1
c table2
d table2
e table2

In general it's appropriate, but can it be done as I showed in necessary result above?


Solution

  • You did not mention any column which will define the order, in that case value column is used to add a ordering using ROW_NUMBER().

    • CTE table1_with_rownum and table2_with_rownum will assign the order.
    • These datasets are then joined based on rownum so that order is maintained and the result sets are unioned to remove any duplicates.

    Fiddle

    WITH table1_with_rownum AS (
        SELECT value, ROW_NUMBER() OVER (ORDER BY value) AS rownum
        FROM table1
    ),
    table2_with_rownum AS (
        SELECT value, ROW_NUMBER() OVER (ORDER BY value) AS rownum
        FROM table2
    )
    
    SELECT 
        t1.value AS value1, 
        t2.value AS value2
    FROM table1_with_rownum t1
    LEFT JOIN table2_with_rownum t2 ON t1.rownum = t2.rownum 
    
    UNION
    
    SELECT 
        t1.value AS value1, 
        t2.value AS value2
    FROM table1_with_rownum t1
    RIGHT JOIN table2_with_rownum t2 ON t1.rownum = t2.rownum
    ORDER BY value1;
    

    Output

    enter image description here