Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How join two tables using SQL without a common column

Tags:

sql-server

Example:

Table 1:

Column1           Column2
-----------       -------------
A                 1
B                 2
D                 3
E                 4

Table 2:

Column3           Column4
-----------       -------------
A                 7
E                 9
Z                 5

Expected output:

Column1           Column2             Column3            Column4
-----------       -------------       -------------      -------------
A                 1                   A                  7
B                 2                   E                  9
D                 3                   Z                  5
E                 4                   NULL               NULL

I want the output as shown in the picture.

If there are two tables with the columns Column1, Coumn2 and Column3, Column4, then the expected output should be Column1, Column2, Column3, Column4, without any joins. It should have Table2's columns to the right hand side of the Table1's columns. NULL values will consume the empty rows if the number of rows in each table don't match.

like image 575
Yasin Avatar asked Aug 18 '15 19:08

Yasin


People also ask

How do I join two tables in different columns in SQL?

Multiple tables can be merged by columns in SQL using joins. Joins merge two tables based on the specified columns (generally, the primary key of one table and a foreign key of the other). Below is the generic syntax of SQL joins. USING (id);

Can we join two tables without any relation SQL?

The answer to this question is yes, you can join two unrelated tables in SQL, and in fact, there are multiple ways to do this, particularly in the Microsoft SQL Server database. The most common way to join two unrelated tables is by using CROSS join, which produces a cartesian product of two tables.

How do you join two tables even if no match?

The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.


1 Answers

You can use ROW_NUMBER window function to create a calculated field that can be used to join the two tables together:

SELECT t1.Column1, t1.Column2, t2.Column3, t2.Column4
FROM (
   SELECT Column1, Column2,
          ROW_NUMBER() OVER (ORDER BY Column1) AS rn
   FROM Table1) AS t1
FULL OUTER JOIN  (
   SELECT Column3, Column4,
          ROW_NUMBER() OVER (ORDER BY Column3) AS rn
   FROM Table2) AS t2
ON t1.rn = t2.rn

A FULL OUTER JOIN is necessary in case either Table1 or Table2 has more rows.

like image 124
Giorgos Betsos Avatar answered Sep 21 '22 19:09

Giorgos Betsos