开发者

SQL insert with select and hard-coded values

开发者 https://www.devze.com 2023-01-24 02:41 出处:网络
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 a

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 th开发者_C百科is:

INSERT INTO Movies 
VALUES(Star Wars,(SELECT name 
                    FROM Directors 
                   WHERE name='Lucas'), 50000, 1000000);

Is this possible?


INSERT INTO Movies (Title, Director, Cost, Profits)
SELECT 'Star Wars', name, 50000, 1000000
FROM Directors WHERE name = 'Lucas'


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';


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';


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消