我有2张桌子
ID, NAME, VALUE 1
ID, NAME, VALUE 2
表A: 编号:A1,A2 名称:AAA,BBB 值1:1000,2000
表B: 编号:B1,B2 名称:CCC,DDD 值1:3000,4000
我想显示这样的结果:
ID,NAME,VALUE 1,VALUE 2 A1 AAA 1000 A2 BBB 2000 A3 CCC 3000 A4 DDD 4000
我尝试了union
,它适用于id, name
列。普通的select + union select
可以吗?
答案 0 :(得分:4)
您可以使用union all
:
select id, name, value1, null as value2
from a
union all
select id, name, null as value1, value2
from b;
答案 1 :(得分:0)
您也可以使用Full Outer Join
SELECT a.id, a.name, a.value1, b.value2
FROM tableA as a
FULL OUTER JOIN tableB AS b ON
a.id = b.id
答案 2 :(得分:0)
MS SQL Server 2017架构设置:
CREATE TABLE Table1
([ID] varchar(2), [NAME] varchar(3), [VALUE1] int)
;
INSERT INTO Table1
([ID], [NAME], [VALUE1])
VALUES
('A1', 'AAA', 1000),
('A2', 'BBB', 2000)
;
CREATE TABLE Table2
([ID] varchar(2), [NAME] varchar(3), [VALUE2] int)
;
INSERT INTO Table2
([ID], [NAME], [VALUE2])
VALUES
('B1', 'CCC', 3000),
('B2', 'DDD', 4000)
;
查询1 :
select id, name, value1, null as value2
from table1
union all
select id, name, null as value1, value2
from table2
Results :
| id | name | value1 | value2 |
|----|------|--------|--------|
| A1 | AAA | 1000 | (null) |
| A2 | BBB | 2000 | (null) |
| B1 | CCC | (null) | 3000 |
| B2 | DDD | (null) | 4000 |