简体   繁体   English

计算后将数据从一个表插入到另一表的过程

[英]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. 我有两个表-1.用户2.小部件“用户”表中有数千个用户。 And I have created a new table named "widgets". 我创建了一个名为“ 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. 现在,每个用户都有5个不同的小部件,我需要在“小部件”表中为“用户”表中的每个条目插入5个条目。 Here is detailed scenario- 这是详细的场景-

"User" Table have column -"id" “用户”表的列-“ id”

"widgets" table have columns- "user_id","widgetId","align","priority" “小工具”表具有以下列:“ user_id”,“ widgetId”,“ align”,“ priority”

and for each user.id I want to insert 5 records into the "widgets" table like this- 对于每个user.id,我想像这样在“ widgets”表中插入5条记录-

1st id from users table, 1,1,1 用户表中的第一个ID 1,1,1

1st id from users table, 2,2,2 用户表中的第一个ID 2,2,2

1st id from users table, 3,3,3 用户表中的第一个ID 3、3、3

1st id from users table, 4,4,4 用户表中的第一个ID 4,4,4

1st id from users table, 5,5,5 用户表中的第一个ID 5,5,5

2nd id from users table, 1,1,1 用户表中的第二个ID 1,1、1

2nd id from users table, 2,2,2 用户表中的第二个ID 2,2,2

2nd id from users table, 3,3,3 用户表中的第二个ID,3、3、3

2nd id from users table, 4,4,4 用户表中的第二个ID 4,4,4

2nd id from users table, 5,5,5 .................... ............... 用户表中的第二个ID 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
      );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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