Oskar Persson
Oskar Persson

Reputation: 6753

Inserting new values combined with a select query using prepared statements

What is the correct syntax for inserting new values combined with a select query using prepared statements?

What I have doesn't work.

INSERT INTO productsUsers
    (product, userId)
VALUES
    (?, SELECT id FROM users WHERE username = ?)

Upvotes: 1

Views: 2173

Answers (2)

Rahul Tripathi
Rahul Tripathi

Reputation: 172398

Try this:-

INSERT INTO productsUsers(product, userId)
SELECT ?,  id 
  FROM users 
  WHERE username = ?)

Check this out for reference

The syntax is:-

INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]

[INTO] tbl_name [(col_name,...)]
SELECT ...
[ ON DUPLICATE KEY UPDATE col_name=expr, ... ]

Upvotes: 0

Trinimon
Trinimon

Reputation: 13957

Just use INSERT INTO...SELECT:

INSERT INTO productsUsers (product, userId)
SELECT ?,  id 
  FROM users 
 WHERE username = ?;

If you want to avoid duplicated id's you could use a ON DUPLICATE KEY clause. Check out the documentation for more.

Upvotes: 7

Related Questions