简体   繁体   English

将两个不同表中的两列插入SQL中的另一个表中

[英]Insert two columns from two different tables into another table in SQL

I have been searching for a solution to my problem for quite a bit, but couldn't find anywhere. 我一直在寻找解决我的问题的方法,但找不到任何地方。 Here is my problem: I have two columns from two different tables and want to insert them into another table which is empty. 这是我的问题:我有两个不同的表中的两列,并希望将它们插入到另一个空的表中。 I have tried to run this query but it doesn't work and I don't even know why: 我试图运行此查询,但它不起作用,我甚至不知道为什么:

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

After running this, I receive the following message: 运行此后,我收到以下消息:

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.

I would also like to add that a.column has 1143 rows, and c.column has 2057 rows. 我还想补充一点,a.column有1143行,c.column有2057行。 Both are PK for their respective tables. 两者都是各自表格的PK。

Any help would be more than appreciated. 任何帮助都不仅仅是值得赞赏的。

Try reframing your query as 尝试重新构建您的查询

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

Would have been better if you provided exact query, but the problem is most likely with the joins. 如果您提供了确切的查询本来会更好,但问题很可能是连接。

I used a set of temp table variables to display the concept, but it should be easily translated to actual tables. 我使用了一组临时表变量来显示概念,但它应该很容易转换为实际的表。

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

Unless you're doing a cartesian join, you've got a mixture of explicit and implicit syntax. 除非您正在进行笛卡尔连接,否则您会混合使用显式和隐式语法。 I would pick one or the other (being partial to explicit syntax myself): 我会选择一个或另一个(我自己偏向显式语法):

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

or whatever works for your structure. 或任何适用于您的结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM