I want to do a INSERT with parameters and some optional values from another table. (With optional I mean that if the subquery fails I want to insert only the parameter values instead of inserting nothing.)
My first attempt was:
INSERT INTO my_table (foo, bar, something)
VALUES (:param, (SELECT bar, something FROM other_table WHERE (foo = :param));
but did not work. The error message was "subselect must have only one field".
Another approach, inspired by this question was:
INSERT INTO my_table (foo, bar, something)
SELECT :param, o.bar, o.something FROM other_table o WHERE o.foo = :param;
But this only performs an INSERT
if it finds something for the WHERE
clause. So it behaves differently from a real subquery. So I came up with this one:
INSERT INTO my_table (foo, bar, something)
VALUES (:param,
(SELECT bar FROM other_table WHERE (foo = :param),
(SELECT something FROM other_table WHERE (foo = :param));
Which works but of course looks unnecessary slow because of two subselects.
So my question is: Can I somehow get this to work with only one subselect.