简体   繁体   中英

How to combine 2 tables and insert values into a 3rd table

I have 2 tables formatted the following ways listed below...

T1

ID   SUB_ID   NAME   NUM
123  ABC      TEST   5
456  XYZ      HELLO  10

T2

ID   SUB_ID   NAME   NUM  CAT  ACTY
123  ABC      TEST   5    sjq  h5h
456  XYZ      HELLO  10   hwl  888

I want to look at these 2 tables and match based on ID and SUB_ID and join them together so I get all the columns from T1 and those columns missing from T1 that are in T2

Both these tables contain thousands of rows but I simplified for this example.

This is the code I have tried but I am getting to many rows back..

SELECT * 
FROM T1 YY
INNER JOIN T2 ZZ
WHERE YY.ID = ZZ.ID and YY.SUB_ID = ZZ.SUB_ID

Any help on how to execute this would be GREATLY appreciated. THANKS!!

I am going to go out on a "guess" here with (THE WHERE CLAUSE IS A GUESS ONLY)

INSERT INTO T3
 (ID, SUB_ID, NAME, NUM, CAT, ACTY)
SELECT T1.ID, T1.SUB_ID, T1.NAME, T1.NUM,
      T2,CAT,  T2.ACTY
FROM T1
INNER JOIN T2
    ON T1.ID = T2.ID 
       AND T1.SUB_ID = T2.SUB_ID
WHERE (T1.ID = 123 AND T1.SUB_ID = 'ABC')
   OR (T1.ID = 456 AND T1.SUB_ID = 'XYZ')

IF T3 has an identity on the ID you may have to alter query to account for that.

In reference to my comment this seems to be the same result:

INSERT INTO T3
 (ID, SUB_ID, NAME, NUM, CAT, ACTY)
SELECT T2.ID, T2.SUB_ID, T2.NAME, T2.NUM, T2,CAT, T2.ACTY
FROM T2
WHERE (T1.ID = 123 AND T1.SUB_ID = 'ABC')
   OR (T1.ID = 456 AND T1.SUB_ID = 'XYZ')

Your code (something similar to below) is correct, but may surprise you if one or the other tables has more than one row with the same ID and SUB_ID.

SELECT * 
FROM T1 YY
INNER JOIN T2 ZZ
WHERE (YY.ID = ZZ.ID AND YY.SUB_ID = ZZ.SUB_ID)

The following example records will return 4 rows, not 2 , because each of the rows in the first table matches 2 rows in the second table.

T1

ID   SUB_ID   NAME   NUM
123  ABC      TEST   5
123  ABC      TEST2  10

T2

ID   SUB_ID   NAME   NUM  CAT  ACTY
123  ABC      TEST   5    sjq  h5h
123  ABC      TEST2  10   hwl  888

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