Reputation: 6753
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
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
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