2010-02-15 57 views
1

我有兩個表(TableA和TableB)。將兩個不同查詢的結果合併爲一個的問題

create table TableA 
(A int null) 

create table TableB 
(B int null) 

insert into TableA 
(A) values (1) 

insert into TableB 
(B) values (2) 

我不能加入他們在一起,但我仍想從他們顯示的結果爲一行。

現在我可以選擇這樣的:

select 
(select A from tableA) as A 
, B from TableB 

結果:

A B 
1 2 

但如果我現在從tableB的刪除:

delete tableB 

現在,當我運行相同的查詢像以前一樣:

select 
(select A from tableA) as A 
, B from TableB 

我看到這一點:

A B 

但我期待從TABLEA看到價值

這樣的:


預期結果:

A B 
1  

爲什麼會發生這種情況,我怎樣才能看到TableA的值,但selectB返回0行?

我使用MS SQL Server 2005的

+0

做了這些答案給你你需要什麼? – 2010-02-18 21:36:49

回答

0

周圍更多的過濾它試試這個:

DECLARE @TableA table (A int null) 
DECLARE @TableB table (B int null) 

insert into @TableA (A) values (1) 
insert into @TableB (B) values (2) 

--this assumes that you don't have a Numbers table, and generates one on the fly with up to 500 rows, you can increase or decrease as necessary, or just join in your Numbers table instead 
;WITH Digits AS 
( 
    SELECT 0 AS nbr 
    UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 
    UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 
    UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 
) 
, AllNumbers AS 
(
    SELECT u3.nbr * 100 + u2.nbr * 10 + u1.nbr + 1 AS Number 
     FROM Digits u1, Digits u2, Digits u3 
     WHERE u3.nbr * 100 + u2.nbr * 10 + u1.nbr + 1 <= 500 
) 
, AllRowsA AS 
(
    SELECT 
     A, ROW_NUMBER() OVER (ORDER BY A) AS RowNumber 
    FROM @TableA 
) 
, AllRowsB AS 
(
    SELECT 
     B, ROW_NUMBER() OVER (ORDER BY B) AS RowNumber 
    FROM @TableB 
) 
SELECT 
    a.A,b.B 
    FROM AllNumbers    n 
     LEFT OUTER JOIN AllRowsA a on n.Number=a.RowNumber 
     LEFT OUTER JOIN AllRowsB b on n.Number=b.RowNumber 
    WHERE a.A IS NOT NULL OR b.B IS NOT NULL 

OUTPUT:

A   B 
----------- ----------- 
1   2 

(1 row(s) affected) 

如果DELETE @TableB,輸出爲:

A   B 
----------- ----------- 
1   NULL 

(1 row(s) affected) 
3

使用LEFT JOIN(儘管它更像是一個交叉的加入你的情況)。

如果你的數據庫支持的話:

SELECT a.a, b.b 
FROM a 
CROSS JOIN b 

如果沒有,這樣做:

SELECT a.a, b.b 
FROM a 
LEFT JOIN b ON (1=1) 

但是,一旦你有更多的排在ab,這將返回笛卡爾乘積:

1 1 
1 2 
2 1 
2 2 
+0

我無法將它們一起加入 - 沒有可以加入的列。 – Imageree 2010-02-15 11:12:02

+0

在SQL Server中我無法使用解決方案1 ​​ - 交叉聯接返回null null。 但是我可以使用解決方案2,如果我確信我只會看到1行。 – Imageree 2010-02-15 11:19:49

0

試試這個:

select a, (select b from b) from a 
union 
select b, (select a from a) from b 

應該找回你所有的現有數據。

您可以通過另一個選擇

1

這實際上會給你你要找的東西,但是如果你只有一排每桌:

select 
(select A from tableA) as A 
, (select B from TableB) as B