0

I have two tables: table_1 contains a post and table_2 contains all users mapped to post. now I would like to insert post into table1 and I will get a post_id, then I will insert all users who are mapped to post with user_id and post_id.

 insert into `post_users_map` (`post_id`,`user_id`,`is_owner`)
 select '12345', `user_id`, '0' from `users`
 where username in ("A","B","C")

Now I would like to insert ("12345",'123',1) as another row along with select results.

Any suggestion is appreciated and Thanks in Advance.

2
  • 1
    How about UNION? Commented Feb 9, 2019 at 9:41
  • Thannk you @Strawberry, UNION worked. Commented Feb 10, 2019 at 12:36

2 Answers 2

2

just use union for add the select

insert into `post_users_map` (`post_id`,`user_id`,`is_owner`) 
select '12345', `user_id`, '0' 
from `users` where username in ("A","B","C")
UNION 
select '12345', '123, '1' 
Sign up to request clarification or add additional context in comments.

Comments

1

Simply add another insert with values after the insert from a select.

insert into `post_users_map` (`post_id`,`user_id`,`is_owner`) 
select 12345, user_id, 0
from `users` 
where username in ('A','B','C');

insert into `post_users_map` (`post_id`,`user_id`,`is_owner`) values 
(12345, 123, 1);

Also, values allows to include more tupples in the same insert.

insert into `post_users_map` (`post_id`,`user_id`,`is_owner`) values 
(12345, 124, 1),
(12345, 125, 1),
(12345, 126, 1);

Or you could use a UNION ALL to insert user_id's from 2 select's with a different is_owner.

insert into `post_users_map` (`post_id`,`user_id`,`is_owner`) 
select 12345, user_id, 0
from `users` 
where username in ('A','B','C')
UNION ALL
select 12345, user_id, 1
from `users` 
where username in ('D');

Comments

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.