tags:

views:

71

answers:

4

This seems so simple, but I just can't figure it out. I want to simply join 2 tables together. I don't care which values are paired with which. Using TSQL, here is an example:

declare @tbl1 table(id int)  
declare @tbl2 table(id int)  

insert @tbl1 values(1)  
insert @tbl1 values(2)  
insert @tbl2 values(3)  
insert @tbl2 values(4)  
insert @tbl2 values(5)  

select * from @tbl1, @tbl2  

This returns 6 rows, but what kind of query will generate this (just slap the tables side-by-side):
1 3
2 4
null 5

+1  A: 

Use Cross Join

  Select * From tableA CrossJoin TableB

But understand you will get a row in the output for every combination of rows in TableA with every Row in TableB...

So if Table A has 8 rows, and TableB has 4 rows, you will get 32 rows of data... If you want any less than that, you have to specify some join criteria, that will filter out the extra rows from the output

Charles Bretana
Same problem as Dave's answer, won't return how he expects.
MPelletier
His example query will give the same answer and he's made it clear that isn't what he wants...
Mark Brittingham
@Mark, The title says "with no join criteria". Clearly, he needs join criteria to do what he wants. That point is what my answer is attempting to communicate.
Charles Bretana
+7  A: 

You can give each table row numbers and then join on the row numbers:

WITH
Table1WithRowNumber as (
    select row_number() over (order by id) as RowNumber, id from Table1
),

Table2WithRowNumber as (
    select row_number() over (order by id) as RowNumber, id from Table2
)

SELECT Table1WithRowNumber.Id, Table2WithRowNumber.Id as Id2
FROM Table1WithRowNumber 
FULL OUTER JOIN Table2WithRowNumber ON Table1WithRowNumber.RowNumber = Table2WithRowNumber.RowNumber

Edit: Modiifed to use FULL OUTER JOIN, so you get all rows (with nulls).

Kirk Woll
I thought about that, but what if he has multiple inserts and deletions? Then his row numbers won't match up. Lots of nulls to be expected.
MPelletier
I think this is what he wants, except, this will only show as many rows as there are on table A
BlackTigerX
@BlackTiger - no, that is why he used a full outer join rather than a left outer join.
Mark Brittingham
+1 You beat me to it Kirk...I was off playing with unpivots before I thought of using RowNumber. My solution is slightly shorter tho ;-)
Mark Brittingham
Thanks; right outer join works too
dudeNumber4
Actually, I should say *in my specific case* right outer join works. For the generic answer to my post, full outer join would be correct.
dudeNumber4
A: 

The SQL1 cross join applies here also.

Select * 
From tableA, TableB
Dave
He explicitly rejected that idea in his question. :)
Kirk Woll
A: 

Well, this will work:

Select A.ID, B.ID From
  (SELECT ROW_NUMBER () OVER (ORDER BY ID) AS RowNumber, ID FROM Tbl2 ) A
full outer join
  (SELECT ROW_NUMBER () OVER (ORDER BY ID) AS RowNumber, ID FROM Tbl1 ) B 
on (A.RowNumber=B.RowNumber)
Mark Brittingham