我有几张表如下 -
表1:
A B C D <<Columns
1 2 3 4 <<single row
表2:
W X Y Z << Columns
5 6 7 8 << Single row
我希望将这两个表组合在一起,它会给我以下结果
结果:
P Q R S << Column headers
1 2 3 4 << row from table1
5 6 7 8 << row from table2
预期结果的列标题为P,Q,R,S和table1中的行以及table2中的行
如何使用SQL实现此目的?
答案 0 :(得分:1)
_更新更严格,更完整,感谢@AntDC(和@Matt)和@Dudu Markovitz __
将UNION
与别名一起使用,如下所示:
SELECT A AS P, B AS Q, C AS R, D AS S
FROM table1
UNION
-- or UNION ALL if you want to keep duplicate rows
SELECT W, X, Y, Z
FROM table2
答案 1 :(得分:1)
select A as P, B as Q, C as R, D as S
from table1
union all
select W,X,Y,Z
from table2
+---+---+---+---+
| p | q | r | s |
+---+---+---+---+
| 1 | 2 | 3 | 4 |
| 5 | 6 | 7 | 8 |
+---+---+---+---+
table2 with 3 Columns
select B as Q, C as R, D as S
from table1
union all
select X,Y,Z
from table2
+---+---+---+
| q | r | s |
+---+---+---+
| 2 | 3 | 4 |
| 6 | 7 | 8 |
+---+---+---+
或
select A as P, B as Q, C as R, D as S
from table1
union all
select null,X,Y,Z
from table2
+--------+---+---+---+
| p | q | r | s |
+--------+---+---+---+
| 1 | 2 | 3 | 4 |
| (null) | 6 | 7 | 8 |
+--------+---+---+---+