简体   繁体   中英

How to combine two tables with different number of columns SQL

I have two tables A and B which look like this:

Table A

col1  col2  ID
--------------
 a     b    1
 c     d    2

Table B

col3  col4  ID
--------------
 x     t    1
 y     u    1
 z     o    2
 m     n    2

I want to create this new table:

Table C

col1 col2 col3  col4  ID
-------------------------
  a    b    x     t    1
  a    b    y     u    1
  c    d    z     o    2
  c    d    m     n    2

The ID's in A are not the unique ID's of those elements in that list. I just need to add a few more properties from their "parent" table(B) in this new table. I know there will be a lot of repetitions but I don't mind that for now.

I tried this following statement:

INSERT INTO C(SELECT A.*, B.col1, B.col2 from A LEFT OUTER JOIN B ON (B.ID = A.ID));

But it is resulting in something I did not expect. The row count of C must be the same as the row count of B. However when I used this SQL query, the resulting tables row count was even more than the total row count of A and B. I'm a beginner in using SQL I would appreciate any help.

A basic JOIN will do:

select
  a.col1,
  a.col2,
  b.col3,
  b.col4,
  a.id
from tablea a
join tableb b on a.id = b.id

If I got you right your tables do not have any relation to each other. So in this case you should be able to do something like this?

Select * from table1, table2

You can also combine this with an insert so you should get your new table

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