SQL 选择使用联合查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4018708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SELECT INTO USING UNION QUERY
提问by Sekhar
I want to create a new table in SQL Server with the following query. I am unable to understand why this query doesn't work.
我想使用以下查询在 SQL Server 中创建一个新表。我无法理解为什么此查询不起作用。
Query1: Works
查询 1:作品
SELECT * FROM TABLE1
UNION
SELECT * FROM TABLE2
Query2: Does not Work.
Error: Msg 170, Level 15, State 1, Line 7
Line 7: Incorrect syntax near ')'.
查询 2:不起作用。错误:Msg 170, Level 15, State 1, Line 7
Line 7: Incorrect syntax near ')'.
SELECT * INTO [NEW_TABLE]
FROM
(
SELECT * FROM TABLE1
UNION
SELECT * FROM TABLE2
)
Thanks!
谢谢!
回答by OMG Ponies
You have to define a table alias for a derived table in SQL Server:
您必须为 SQL Server 中的派生表定义表别名:
SELECT x.*
INTO [NEW_TABLE]
FROM (SELECT * FROM TABLE1
UNION
SELECT * FROM TABLE2) x
"x" is the table alias in this example.
“x”是本例中的表别名。
回答by Lorena Pita
INSERT INTO #Temp1
SELECT val1, val2
FROM TABLE1
UNION
SELECT val1, val2
FROM TABLE2
回答by lucazarts25
Here's one working syntax for SQL Server 2017:
这是 SQL Server 2017 的一种工作语法:
USE [<yourdb-name>]
GO
SELECT * INTO NEWTABLE
FROM <table1-name>
UNION ALL
SELECT * FROM <table2-name>
回答by Pablo Santa Cruz
You can also try:
你也可以试试:
create table new_table as
select * from table1
union
select * from table2
回答by Jim
select *
into new_table
from table_A
UNION
Select *
From table_B
This only works if Table_A and Table_B have the same schemas
这只适用于 Table_A 和 Table_B 具有相同模式的情况