Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert into with select (prepared statement)

Tags:

sql

mysql

I want this query:

INSERT INTO
    users_groups (user_id, group_id)
VALUES
    (?, (SELECT group_id FROM groups WHERE group_name = ?))

tables:

users_groups:
| user_id | group_id |

groups
| group_id | group_name |

How can I get this working?

like image 848
Bernd Avatar asked Oct 16 '25 02:10

Bernd


2 Answers

Try this;

INSERT INTO
    users_groups (user_id, group_id)
VALUES
    (SELECT ?, group_id FROM groups WHERE group_name = ?)
like image 77
Praveen Avatar answered Oct 18 '25 21:10

Praveen


Leave 'VALUES' out of your statement. What do you mean with the '?'; parameters? Try the script beneath. Does that serve your purpose?

 INSERT INTO
 users_groups (group_id)
 SELECT group_id FROM groups WHERE group_name = [YOUR SELECTION]

Something like that (?). Or what do you mean exactly what you want to work? (PS: due to not enough rep points I can't add comments, so I have to ask the question here; I'll delete it later if answered)

like image 32
cybork Avatar answered Oct 18 '25 19:10

cybork



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!