mahdi pishguy mahdi pishguy - 3 months ago 11
MySQL Question

combine select id from other table with insert on single command

For inserting single row in database i have to get userId from other table, for doing this action i use

SELECT
nested insert.

but i dont know how can i get userId from
SELECT
section and put that on
INSERT
of
VALUES
, for example:

INSERT INTO notifications (
userId ,
type ,
createdAt ,
updatedAt
SELECT id FROM users WHERE username = 'USERNAME'
) VALUES (?, ?, 'CURRENT_TIMESTAMP' , 'CURRENT_TIMESTAMP');


for first column of notifications table i have too get userId from
SELECT
command, and put it on that,

how can i do that?

Answer

You should use an insert select eg: this way

INSERT INTO notifications ( userId ,   type ,   createdAt ,  updatedAt) 
SELECT id, ? ,  'CURRENT_TIMESTAMP' , 'CURRENT_TIMESTAMP'
FROM users WHERE username = 'USERNAME'