简体   繁体   English

从多行插入MS SQL

[英]MS SQL Insert from multiple rows

I´m trying to insert values into a database from several tables: 我正在尝试从多个表中将值插入数据库:

insert dbo.Table1
(ID, IDTable2, IDCounter)
select
s.ID
o.IDTable2
o.IDCounter
from dbo.table3 as o, dbo.table2 as s

But the above code leads to the situation that i get duplicate values for the values from table 3, where i just want one value from table3 per value from table 2. (The tables don´t have any relationship info) 但是上面的代码导致我从表3中获得重复的值,在这种情况下,我只希望从表3中获得每个表2中的一个值。(这些表没有任何关系信息)

Thanks in advance. 提前致谢。

Edit: 编辑:

Thanks everyone. 感谢大家。 I managed to solve it by adding a reference id to table2 and then using an inner join. 我设法通过在表2中添加引用ID并使用内部联接来解决该问题。

You should not use full join as this will lead to table3 rows x table2 rows. 您不应该使用完全连接,因为这将导致table3行x table2行。 Use inner join instead. 请改用内部联接。

You forgot the clause for joining the tables table2 and table3, thus building a cartesian product. 您忘记了连接表table2和table3的子句,因此建立了笛卡尔积。 There must be something linking the tables; 必须有一些表链接起来; otherwise it makes no sense to combine them as you do. 否则,将它们像您那样合并是没有意义的。

My advice: Stay away from that old join syntax where you list the tables comma-separated. 我的建议:远离那种以逗号分隔列出表的旧联接语法。 Use up-to-date join syntax (INNER JOIN ON etc.) instead. 而是使用最新的联接语法(INNER JOIN ON等)。

Having said this, I don't see how your select will make sense anyhow. 话虽如此,我仍然看不出您的选择如何有意义。 ID is to become the ID of table2 and IDTable2 is to become the ID of table2, too? ID也要成为table2的ID,IDTable2也要成为table2的ID?

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

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