SQL insert with select and hard-coded values

2019-04-18 14:57发布

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.

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?

标签: sql mysql insert
4条回答
SAY GOODBYE
2楼-- · 2019-04-18 15:02

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.

查看更多
Ridiculous、
3楼-- · 2019-04-18 15:05

Because you can specify hardcoded values in the select statement, it's probably cleaner to use:

insert into movies (title, director, cost, profits)
   select 'Star Wars', name, 50000, 1000000 from directors where name = 'Lucas';
查看更多
走好不送
4楼-- · 2019-04-18 15:09

Yes, this is possible. User INSERT .. SELECT syntax. See reference for more details. The hard coded values should be in your SELECT query rather than inside the VALUES. E.g.

INSERT INTO Movies
SELECT 'Star Wars', name, 50000, 1000000
FROM Directors 
WHERE name = 'Lucas';
查看更多
何必那么认真
5楼-- · 2019-04-18 15:19
INSERT INTO Movies (Title, Director, Cost, Profits)
SELECT 'Star Wars', name, 50000, 1000000
FROM Directors WHERE name = 'Lucas'
查看更多
登录 后发表回答