[英]How to insert data from source table (but different columns) into two different tables in SQL Server
[英]Insert two columns from two different tables into another table in SQL
我一直在寻找解决我的问题的方法,但找不到任何地方。 这是我的问题:我有两个不同的表中的两列,并希望将它们插入到另一个空的表中。 我试图运行此查询,但它不起作用,我甚至不知道为什么:
SELECT a.column, c.column
FROM FirstTable.column a, SecondTable.column c
left outer join ThirdTable.column b on a.column = b.column
left outer join ThirdTable.column b on c.column = b.column
运行此后,我收到以下消息:
Msg 4104, Level 16, State 1, Line 3
The multi-part identifier "a.column" could not be bound.
Msg 1011, Level 16, State 1, Line 1
The correlation name 'b' is specified multiple times in a FROM clause.
我还想补充一点,a.column有1143行,c.column有2057行。 两者都是各自表格的PK。
任何帮助都不仅仅是值得赞赏的。
尝试重新构建您的查询
SELECT a.column, c.column
FROM Table a left outer join Table b on a.column = b.column
left outer join Table c on c.column = b.column
如果您提供了确切的查询本来会更好,但问题很可能是连接。
我使用了一组临时表变量来显示概念,但它应该很容易转换为实际的表。
DECLARE @tabl1 TABLE (col1 int DEFAULT 1)
INSERT INTO @tabl1 VALUES (1)
DECLARE @tabl2 TABLE (col2 int DEFAULT 2)
INSERT INTO @tabl2 VALUES (2)
DECLARE @tabl3 TABLE (col1 int, col2 int)
-- This should be what you need.
INSERT INTO @tabl3
SELECT a.col1
, b.col2
FROM @tabl1 a, @tabl2 b
SELECT * FROM @tabl3
除非您正在进行笛卡尔连接,否则您会混合使用显式和隐式语法。 我会选择一个或另一个(我自己偏向显式语法):
SELECT a.column, c.column
FROM Table a
left outer join Table b on a.column = b.column
left outer join Table c on b.column = c.column
或任何适用于您的结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.