简体   繁体   English

SQL INSERT INTO结合值和选择失败

[英]Sql INSERT INTO combining value and select failure

I wanted to insert two values, one is filled by a fixed number and the other one is the id from another table. 我想插入两个值,一个由固定数字填充,另一个是另一个表的ID。

Now I got the error 现在我得到了错误

#1242 - Subquery returns more than 1 row. #1242-子查询返回的行数超过1。

INSERT INTO table1 (value1, value2) VALUES 
(6 , (SELECT id FROM table2 WHERE name = 'Peter'))

Maybe you can help me. 也许你可以帮我。

If you want to insert record into your table1 for every record in table2 where name is Peter this approach should work. 如果要为table2中名称为Peter的每个记录插入记录到table1中,则此方法应该有效。

This insert query will insert all records from table2 where name is "Peter" into table1. 此插入查询将表2中名称为“ Peter”的所有记录插入表1中。 If you want to insert only one record you could use LIMIT as Macmee has explained in his answer 如果您只想插入一条记录,则可以使用LIMIT如Macmee在其回答中所述

insert into dbo.table1
(
     value1,
     value2
)(
     select 
          6,
          table2.id 
     from 
          table2
     where
          name = 'Peter'
)

try using LIMIT 1 : 尝试使用LIMIT 1

INSERT INTO table1 (value1, value2) VALUES (6 , (SELECT id FROM table2 WHERE name = 'Peter' LIMIT 1))

This way in your nested query (SELECT id FROM table2 WHERE name = 'Peter' LIMIT 1) it will only return the first match, and your insert should go through. 这样,在嵌套查询中(SELECT id FROM table2 WHERE name = 'Peter' LIMIT 1) ,它将仅返回第一个匹配项,并且插入应通过。

Keep in mind that if your intent was to insert new rows for EVERY row in table2 who's name is "Peter" then this will only insert the first one. 请记住,如果您打算为table2中名为“ Peter”的每一行插入新行,则只会插入第一行。

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

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