Zubair Mushtaq
Zubair Mushtaq

Reputation: 323

How to insert the values in one table by getting the id from other table

I want to add a seprate popup for every user from the tbl_users in the tbl_pop_up_messages. For example, If I have 50 users in tbl_users, 50 rows should be added in the tbl_pop_up_messages against every user.S that, every logged in user will see the popup and the popup will be deactivated after the clic.My conern is only to add the rows. Kindly, guide.

SELECT user_id FROMt bl_users;
INSERT INTO tbl_pop_up_messages (user_id, popup_text, active) 
VALUES  ('3', 'Pop Up Text', '1');

Upvotes: 1

Views: 65

Answers (2)

Radu Gheorghiu
Radu Gheorghiu

Reputation: 20499

You can do it with an INSERT INTO SELECT, like below, provided you have a table with popup messages that you want to be added to each user:

INSERT INTO tbl_pop_up_messages (user_id, popup_text, active)
SELECT usr.user_id
    , pmt.popup_text
    , 1 
FROM tbl_users usr
    cross join popup_messages_table pmt

Alternatively, you can use a more .. "direct" and long approach, in case you don't have a popup messages table, like below:

INSERT INTO tbl_pop_up_messages (user_id, popup_text, active)
SELECT usr.user_id
    , pmt.popup_text
    , 1 
FROM tbl_users usr
    cross join (select 'Pop Up Text' popup_text
               union all
               select '2nd Pop Up Text'
               union all
               select '3rd Pop Up Text'
               -- and so on until you reach X messages or how many you want for each user
              ) pmt

If you need to insert only one popup text message for each user, then:

INSERT INTO tbl_pop_up_messages (user_id, popup_text, active)
SELECT usr.user_id, 'Pop Up Text', '1'
FROM tbl_users

Upvotes: 2

Gordon Linoff
Gordon Linoff

Reputation: 1269933

You can do this as:

INSERT INTO tbl_pop_up_messages(user_id, popup_text, active) 
    SELECT  u.user_id, 'Pop Up Text', '1'
    FROM tbl_users u;

Upvotes: 1

Related Questions