简体   繁体   English

根据来自多个其他表的数据动态生成 SQL Insert Rows 数据

[英]Generate SQL Insert Rows data dynamically based on data from multiple other tables

I am having total of 6 tables say example table1, table3, table3, table4, table5, table6我总共有 6 个表,例如 table1、table3、table3、table4、table5、table6

I am having a peculiar problem, where i need to generate data for table 6 using data from table 1 to 5.我有一个特殊的问题,我需要使用表 1 到表 5 中的数据为表 6 生成数据。

Where subset of data comes from table 1-4 and another subset comes from table 5, now i need to find a way to merge these data from table 1-4 and table 5 to insert data dynamically into table 6.其中数据子集来自表 1-4,另一个子集来自表 5,现在我需要找到一种方法来合并表 1-4 和表 5 中的这些数据,以将数据动态插入表 6。

to give example, from table 1 to 4 i am able to select the data and retrive where in one of the columns of this data has value in integer form like 2,2,3,4 etc kind.举个例子,从表 1 到 4,我能够 select 数据并检索该数据的其中一列中的 integer 形式的值,如 2、2、3、4 等。

So if i have 4 rows for table 1 to 4, where column1 has values 2, 2, 3, 4 then it implies i have to loop through 2,2,3,4 times each along with data from table 5 and then insert into table 6.因此,如果表 1 到 4 有 4 行,其中 column1 的值为 2、2、3、4,那么这意味着我必须与表 5 中的数据一起循环 2、2、3、4 次,然后插入表 6。

so in this case my table 1-4 has 4 rows with column 1 having 2,2,3,4 values and table 5 has 10 rows in this case my table 6 will have ((2+2+3+4)*10=110) 110 rows to be inserted.所以在这种情况下,我的表 1-4 有 4 行,第 1 列有 2,2,3,4 值,表 5 有 10 行,在这种情况下,我的表 6 将有 ((2+2+3+4)*10 =110) 要插入 110 行。

I am facing challenge in generating insert rows data for table 6 dynamically based on values from table 1-4, table 5.我在根据表 1-4、表 5 中的值动态生成表 6 的插入行数据时面临挑战。

i believe couple of for loops is required, one to loop through table 1-4, and one more to loop through table 5 and generate the 110 insert rows.我相信需要几个 for 循环,一个循环遍历表 1-4,另一个循环遍历表 5 并生成 110 个插入行。 I am trying to achieve this using python and DB is postgres.我正在尝试使用 python 来实现这一点,而 DB 是 postgres。

It sounds like a cross join :这听起来像一个cross join

with t1_4 as (
      <whatever where is on the first four tables>
     )
select . . .
from t1_4 cross join lateral
     generate_series(1, t1_4.col1, 1) as gs(n) cross join
     t5

You can insert the results into table6 or use create table as depending on what you really need to do.您可以将结果插入table6或使用create table as取决于您真正需要做的事情。

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

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