0

I'm trying to insert several records like this :

SET @user_id = (select `id` from users where `email` IN( '[email protected]', '[email protected]' ) );

SET @badge_id = (select `id` from badges where `slug` = 'elearning_nutrition');

INSERT INTO `instructor_badges` (`id`, `user_id`, `badge_id`, `is_active`, `is_manual`, `created`)
VALUES (UUID(), @user_id, @badge_id, '1', '0', NOW());

but im getting this error:

[ERROR in query 1] Subquery returns more than 1 row

In this case I would have to insert 2 records. How could I perform this query?

1
  • You want to insert two records? Or you just want to defeat the "Subquery returns more than 1 row" error? In the second case, just put "LIMIT 1" onto your subqueries. Commented Apr 24, 2015 at 19:04

2 Answers 2

1

You could try this. This will cartesian join users to badges, though. So if you select two users and two badges you will get four rows to insert. But I think that's what you are saying you want to achieve.

INSERT INTO instructor_badges (id, user_id, badge_id, is_active, is_manual, created)
SELECT UUID(), users.id, badges.id, '1', '0', NOW()
FROM users 
JOIN badge
WHERE users.email IN( '[email protected]', '[email protected]' )
&& badges.slug = 'elearning_nutrition'
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you in my case the badge is only one . What do you think if I do something like this which I see is working as well. SET @badge_id = (select id from badges where slug = 'elearning_nutrition'); INSERT INTO instructor_badges (user_id, id, badge_id, is_active, is_manual, created) select id , UUID(), @badge_id , '1', '0', NOW() from users where email IN( '[email protected]', '[email protected]' )
Yes, that looks lovely to me.
Note that you can also just use your subquery directly if you would like to avoid the @badge_id variable.
0

OK I solved in this way , is there another better way because I had to write user_id in first position :

 SET @badge_id = (select `id` from badges where `slug` = 'elearning_nutrition');

INSERT INTO `instructor_badges` (`user_id`, `id`,  `badge_id`, `is_active`, `is_manual`, `created`)
select `id` , UUID(), @badge_id , '1', '0', NOW() from users where `email`   IN( '[email protected]', '[email protected]' ) 

2 Comments

Why did you have to write it in first position?
In the future, you can just edit my Answer rather than providing your own so that we get more consensus on the right answer. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.