开发者

Combine 2 result sets in SQL?

How do I combine the resultsets to return a single result in SQL? For example -

SELECT * FROM Table1
SELECT * FROM Table2

I want to combine the two resultsets with the columns from the second resultset appended to the first.

Table 1 and Table 2 are not related to each other in any way. If Table 1 has 2 columns and Table 2 has 4 columns, I wanted 6 columns returned total in a single resultset. And if Table 1 has 4 rows and Table 2 has only 2 rows, I want NULLS in Table 2 rows for 3rd and 4th row.

Is it po开发者_如何学Gossible?

Edit: I do not know how many columns are present in Table1 and Table2, so cannot use UNION with nulls.


If your RDBMS supports ROW_NUMBER() you could do something like this.

WITH T1 AS
(
SELECT *, ROW_NUMBER() OVER ( ORDER BY T1id) AS RN1 FROM Table1
),
T2 AS
(
SELECT *, ROW_NUMBER() OVER ( ORDER BY T2id) AS RN2 FROM Table2
)


SELECT * FROM T1 FULL OUTER JOIN T2 ON RN1 =RN2


It's possible but it's probably quite a bad idea to do this. Why not just run two queries?

If you really want to do it, join the two result sets on a ROW_NUMBER() field.


Not a general solution, but works if you know your schema:

select a1, a2, null as b1, null as b2 from table1
union
select null as a1, null as a2, b1, b2 from table2
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜