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

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


You can do this by creating a key, which is the row number, and joining on it.

Most dialects of SQL support the row_number() function. Here is an approach using it:

select gu.id, gu.name, gi.id, gi.namefrom (select g.*, row_number() over (order by id) as seqnum      from guys g     ) gu full outer join     (select g.*, row_number() over (order by id) as seqnum      from girls g     ) gi     on gu.seqnum = gi.seqnum;


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 girlnameFROM guys2 FULL OUTER JOIN girls2 ON guys2.rn = girls2.rnORDER BY COALESCE(guys2.rn, girls2.rn);

An SQLfiddle to test with.


Assuming, you want to match guys up with girls in your example, and have some sort of meaningful relationship between the records (no pun intended)...

Typically you'd do this with a separate table to represent the association (relationship) between the two.

enter image description here

This wouldn't give you a physical table, but it would enable you to write an SQL query representing the final results:

SELECT     Girls.ID AS GirlId, Girls.Name AS GirlName, Guys.ID AS GuyId, Guys.Name AS GuyNameFROM         Couples INNER JOIN             Girls ON Couples.GirlId = Girls.ID INNER JOIN             Guys ON Couples.GuyId = Guys.ID

which you could then use to create a table on the fly using the Select Into syntax

  SELECT     Girls.ID AS GirlId, Girls.Name AS GirlName, Guys.ID AS GuyId, Guys.Name AS GuyName    INTO MyNewTable    FROM         Couples INNER JOIN                 Girls ON Couples.GirlId = Girls.ID INNER JOIN                 Guys ON Couples.GuyId = Guys.ID

(But standard Normalization rules would say it's best to keep them in distinct tables rather than creating a temp table, unless there's a performance reason not to do so.)