Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert multiple rows with a subquery as one of the value?

I'm trying to insert multiple rows to a table where the value of one column is from another query. However I got the following error

more than one row returned by a subquery used as an expression

How should I do this ?

INSERT INTO 
   accounts_account_preferences (account_id, preference_id) 
VALUES 
   ((SELECT account_id 
     FROM accounts_account_preferences 
     WHERE preference_id = 1), 2);
like image 530
vincentf Avatar asked Oct 31 '25 09:10

vincentf


1 Answers

Use INSERT ... SELECT ... without VALUES:

INSERT INTO accounts_account_preferences (account_id, preference_id) 
SELECT account_id, 2 
FROM accounts_account_preferences 
WHERE preference_id = 1
like image 138
klin Avatar answered Nov 03 '25 00:11

klin



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!