将2个SQL表与相同的列组合在一起

时间:2014-10-30 19:03:31

标签: sql sql-server sql-server-2008

我在sql-server-2008中有两个sql视图。两者都有ITEM_NOQTYLOCATION列。

view_1:

-----------------------------------
|  ITEM_NO  |  QTY  |  LOCATION   | 
-----------------------------------
|  SN-15    |   0   |    SEA      |
-----------------------------------
|  XY-45    |   2   |    SFO      |
-----------------------------------
|  TY-14    |   1   |    SEA      |
-----------------------------------

view_2:

-----------------------------------
|  ITEM_NO  |  QTY  |  LOCATION   | 
-----------------------------------
|  HN-34    |   1   |    SEA      |
-----------------------------------
|  GJ-13    |   4   |    SFO      |
-----------------------------------
|  RB-02    |   7   |    SEA      |
-----------------------------------
|  AJ-13    |   9   |    LAX      |
-----------------------------------

我想将这些组合成一个视图,如下所示:

-----------------------------------
|  ITEM_NO  |  QTY  |  LOCATION   | 
-----------------------------------
|  SN-15    |   0   |    SEA      |
-----------------------------------
|  XY-45    |   2   |    SFO      |
-----------------------------------
|  TY-14    |   1   |    SEA      |
-----------------------------------
|  HN-34    |   1   |    SEA      |
-----------------------------------
|  GJ-13    |   4   |    SFO      |
-----------------------------------
|  RB-02    |   7   |    SEA      |
-----------------------------------
|  AJ-13    |   9   |    LAX      |
-----------------------------------

有一种简单的方法吗?

3 个答案:

答案 0 :(得分:1)

试试这个

SELECT ITEM_NO, QTY, LOCATION
FROM view_1

UNION ALL

SELECT ITEM_NO, QTY, LOCATION
FROM view_2

答案 1 :(得分:1)

您可以使用UNION ..

SELECT ITEM_NO, QTY, LOCATION from View_1
UNION
SELECT ITEM_NO, QTY, LOCATION from View_2

,如果您不关心重复,更有效的方法是UNION ALL

SELECT ITEM_NO, QTY, LOCATION from View_1
UNION ALL
SELECT ITEM_NO, QTY, LOCATION from View_2

UNION将在内部执行DISTINCT,而UNION ALL则不会,因此效果会更好。您还应注意,如果您希望ORDER BY对整个结果集进行排序,则ORDER BY需要放置在查询的 END 处。

答案 2 :(得分:1)

UNION用于组合多个SELECT语句的结果集。

SELECT * 
FROM View_1
UNION
SELECT * 
FROM View_2

Documentation