A
A
Artem2016-12-16 16:53:08
SQL
Artem, 2016-12-16 16:53:08

How to conduct an insert if one of the inserted values ​​needs to be found using SELECT?

Hello.
There are 2 tables:
requests - id, file_id, the rest is not important.
files - id, name
I have table name file as input. How to build an insert request so that in the end I get the id of the file as the second parameter, and not its name?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Melkij, 2016-12-16
@melkij

insert into requests (file_id /*other*/) values((select id from tablename where name = ?) /*, other*/);

NULL if there are no rows in the subquery, an error - if there are more than 1 rows.
insert into requests (file_id /*other*/) 
select id, /* other const values*/ from tablename where name = ?;

If select gives 0 rows, nothing will be inserted.
One or more - so many new lines will be inserted.

A
Anton, 2016-12-16
@MoonMaster

Maybe in this case, use the INSERT INTO SELECT construct

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question