MySQL INSERT INTO ... VALUES 和 SELECT

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15523597/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 16:58:40  来源:igfitidea点击:

MySQL INSERT INTO ... VALUES and SELECT

mysqlsqlselectinsert

提问by TheEnigmist

Is there a way to insert pre-set values and values I get from a select-query? For example:

有没有办法插入预设值和我从选择查询中获得的值?例如:

INSERT INTO table1 VALUES ("A string", 5, [int]).

I have the value of "A string" and the number 5, but I've to find the [int] value from a select like this:

我有“A string”的值和数字 5,但我必须从这样的选择中找到 [int] 值:

SELECT idTable2
FROM table2
WHERE ...

that gives me that id to put inside table1.

这给了我可以放入 table1 的 ID。

How to merge this into one statement?

如何将其合并为一个语句?

回答by Guffa

Use an insert ... selectquery, and put the known values in the select:

使用insert ... select查询,并将已知值放入select

insert into table1
select 'A string', 5, idTable2
from table2
where ...

回答by zoujyjs

just use a subquery right there like:

只需在那里使用子查询,例如:

INSERT INTO table1 VALUES ("A string", 5, (SELECT ...)).

回答by Mahbub Tito

 
INSERT INTO table_name1
            (id,
             name,
             address,
             contact_number) 
SELECT id, name, address, contact_number FROM table_name2;   

回答by echo_Me

try this

尝试这个

INSERT INTO TABLE1 (COL1 , COL2,COL3) values
('A STRING' , 5 , (select idTable2 from Table2) )
where ...

回答by Felypp Oliveira

All other answers solves the problem and my answer works the same way as the others, but just on a more didactically way (this works on MySQL... don't know other SQL servers):

所有其他答案都解决了这个问题,我的答案与其他答案的工作方式相同,但只是以更具教学性的方式(这适用于 MySQL ... 不知道其他 SQL 服务器):

INSERT INTO table1 SET 
  stringColumn  = 'A String', 
  numericColumn = 5, 
  selectColumn  = (SELECT idTable2 FROM table2 WHERE ...);

You can refer the MySQL documentation: INSERT Syntax

可以参考 MySQL 文档:INSERT Syntax

回答by Jono Guthrie

INSERT INTO table1 
SELECT "A string", 5, idTable2
FROM table2
WHERE ...

See: http://dev.mysql.com/doc/refman/5.6/en/insert-select.html

见:http: //dev.mysql.com/doc/refman/5.6/en/insert-select.html

回答by Laurent S.

INSERT INTO table1 (col1, col2)
SELECT "a string", 5, TheNameOfTheFieldInTable2
FROM table2 where ...

回答by Korhan Ozturk

Try the following:

请尝试以下操作:

INSERT INTO table1 
SELECT 'A string', 5, idTable2 idTable2 FROM table2 WHERE ...

回答by neelsg

Try this:

尝试这个:

INSERT INTO table1 SELECT "A string", 5, idTable2 FROM table2 WHERE ...