Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql merge tables side-by-side with nothing in common

Tags:

sql

I'm looking for an sql answer on how to merge two tables without anything in common.

So let's say you have these two tables without anything in common:

Guys                Girls
id    name          id   name
---  ------        ----  ------
1     abraham        5    sarah
2     isaak          6    rachel
3     jacob          7    rebeka
                     8    leah

and you want to merge them side-by-side like this:

Couples

id   name      id   name
---  ------    ---  ------
1    abraham   5    sarah
2    isaak     6    rachel
3    jacob     7    rebeka
               8    leah

How can this be done?

I'm looking for an sql answer on how to merge two tables without anything in common.

like image 954
Mike Avatar asked Jul 12 '13 18:07

Mike


People also ask

How do you combine two tables without common fields?

One way to join two tables without a common column is to use an obsolete syntax for joining tables. With this syntax, we simply list the tables that we want to join in the FROM clause then use a WHERE clause to add joining conditions if necessary.

How do I join tables side by side in SQL?

Merging tables by columns. 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.

Can we join two tables with null values?

Null values in tables or views being joined never match each other. Since bit columns do not permit null values, a value of 0 appears in an outer join when there is no match for a bit column in the inner table. The result of a join of null with any other value is null.

How do I combine data from multiple tables into one table in SQL?

SQL JOIN. A JOIN clause is used to combine rows from two or more tables, based on a related column between them. Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the "Customers" table. The relationship between the two tables above is the "CustomerID" column.


1 Answers

Just because I wrote it up anyway, an alternative using CTEs;

WITH guys2 AS ( SELECT id,name,ROW_NUMBER() OVER (ORDER BY id) rn FROM guys), 
    girls2 AS ( SELECT id,name,ROW_NUMBER() OVER (ORDER BY id) rn FROM girls)
SELECT  guys2.id guyid,   guys2.name guyname, 
       girls2.id girlid, girls2.name girlname
FROM guys2 FULL OUTER JOIN girls2 ON guys2.rn = girls2.rn
ORDER BY COALESCE(guys2.rn, girls2.rn);

An SQLfiddle to test with.

like image 99
Joachim Isaksson Avatar answered Sep 28 '22 08:09

Joachim Isaksson