简体   繁体   中英

How can I join data from two tables and insert the result into a new table?

I have a table for my products and my key is Pid .

Each product can have several types of modes that are registered in the table TB_Types .

did is an identity column (key), pid is foreign key to products table:

did pid name
1 1 type1
2 1 type2
3 2 type3
4 2 type4

Now we have a table where each product can have a different number table name: TB_Count

Like the table below:

cid is an identity column (key), pid is a foreign key to the products table

cid pid count
1 1 25
2 1 50
3 1 100
6 2 1000
7 2 5000
8 2 10000

Initially, the customer wanted each product to have different types and numbers, but now the count table must be changed as follows and the count that was for each product must be for each type.

I created a table as it should be.

New table name: tb_newcount

id is an identity column (key), did is a foreign key to the TB_Types table.

id did count
1 1 25
2 1 50
3 1 100
4 2 25
5 2 50
6 2 100
7 3 5000
8 3 10000
9 3 15000
10 4 5000
11 4 10000
12 4 15000

If I can move the information to the new table as it was said, the problem will be solved.

I hope I have said what I mean.

Note: The number of products is close to 5,000 and the number of types is 2000 and the number of count is about 2000 records.

thanks

You need INNER JOIN as follows:

INSERT INTO tb_newcount (did, count)
select did, count
  from TB_Types t join TB_Count c on c.pid = t.pid

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