将两个不同查询的结果合二为一的问题

时间:2010-02-15 11:09:25

标签: sql sql-server sql-server-2005

我有两个表(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    

为什么会发生这种情况,虽然selectB返回0行,但仍然可以看到TableA中的值?

我正在使用MS SQL Server 2005。

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

这实际上会为您提供所需的内容,但如果每个表只有一行:

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

答案 2 :(得分:0)

试试这个:

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

应检索所有现有数据。

你可以通过用另一个选择

包围它来更多地过滤它

答案 3 :(得分: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

输出:

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

(1 row(s) affected)

如果您DELETE @TableB,则输出为:

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

(1 row(s) affected)