简体   繁体   中英

Procedure to insert a data from one table to another table after calculations

I have two table- 1. user 2. widgets There are thousand of users in "user" table. And I have created a new table named "widgets". Now Every user have 5 different widgets and I need to insert 5 entries into the "widgets" table for each entry in the "user" table. Here is detailed scenario-

"User" Table have column -"id"

"widgets" table have columns- "user_id","widgetId","align","priority"

and for each user.id I want to insert 5 records into the "widgets" table like this-

1st id from users table, 1,1,1

1st id from users table, 2,2,2

1st id from users table, 3,3,3

1st id from users table, 4,4,4

1st id from users table, 5,5,5

2nd id from users table, 1,1,1

2nd id from users table, 2,2,2

2nd id from users table, 3,3,3

2nd id from users table, 4,4,4

2nd id from users table, 5,5,5 .................... ...............

I want to create a procedure for doing the same. Please Someone suggest me how can I do this.

I would suggest a separate table for the defaults. This will not only allow the defaults to be easily adapted as the business needs and offerings grow, but also allow for a template that can be used for other purposes.

create table DefaultWidgets (widgetid INT, align INT, priority INT);
insert into DefaultWidgets values (1,1,1);
insert into DefaultWidgets values (2,2,2);
insert into DefaultWidgets values (3,3,3);
insert into DefaultWidgets values (4,4,4);
insert into DefaultWidgets values (5,5,5);

insert into widgets values (1,1,100,100);
-- mainly to demonstrate that a new row won't be inserted for user 1, widget 1.

INSERT INTO widgets
  SELECT id, r.widgetid, r.align, r.priority
  FROM users u
    CROSS JOIN DefaultWidgets R
  WHERE NOT EXISTS (
      SELECT 1
      FROM widgets w
      WHERE userid = u.id
        AND w.widgetid=R.widgetid
      );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM