MySQL 带有选择和硬编码值的 SQL 插入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4141370/
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
SQL insert with select and hard-coded values
提问by Msencenb
For illustration purposes, let's say I have a database Movies(Title, Director, Cost, Profits).
出于说明目的,假设我有一个数据库电影(标题、导演、成本、利润)。
Now I would like to insert a new row into the Movies table based on a director found in another table and then hard coded values.
现在我想根据在另一个表中找到的导演然后硬编码值在 Movies 表中插入一个新行。
INSERT INTO Movies
SELECT name
FROM Directors
WHERE name = 'Lucas';
Is how I understand select inserts work but what if I want to use the select as well as pass in hard coded values. So something theoretically like this:
我是如何理解选择插入工作的,但是如果我想使用选择并传入硬编码值怎么办。所以理论上是这样的:
INSERT INTO Movies
VALUES(Star Wars,(SELECT name
FROM Directors
WHERE name='Lucas'), 50000, 1000000);
Is this possible?
这可能吗?
回答by Phil
INSERT INTO Movies (Title, Director, Cost, Profits)
SELECT 'Star Wars', name, 50000, 1000000
FROM Directors WHERE name = 'Lucas'
回答by paxdiablo
Because you can specify hardcoded values in the select
statement, it's probably cleaner to use:
因为您可以在select
语句中指定硬编码值,所以使用它可能更清晰:
insert into movies (title, director, cost, profits)
select 'Star Wars', name, 50000, 1000000 from directors where name = 'Lucas';
回答by Manny
Yes, this is possible. User INSERT .. SELECT syntax. See referencefor more details. The hard coded values should be in your SELECT query rather than inside the VALUES. E.g.
是的,这是可能的。用户 INSERT .. SELECT 语法。有关更多详细信息,请参阅参考资料。硬编码值应该在您的 SELECT 查询中,而不是在 VALUES 中。例如
INSERT INTO Movies
SELECT 'Star Wars', name, 50000, 1000000
FROM Directors
WHERE name = 'Lucas';
回答by Cold-Blooded
you have database as Movies(Title, Director, Cost, Profits). if u want to enter the values in the respective tables then first select the table and then insert values in those tables.
你有数据库作为电影(标题,导演,成本,利润)。如果您想在相应的表中输入值,则首先选择该表,然后在这些表中插入值。