[英]How to combine two tables with different number of columns SQL
I have two tables A and B which look like this:我有两个表 A 和 B,它们看起来像这样:
Table A表A
col1 col2 ID
--------------
a b 1
c d 2
Table B表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表 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. A 中的 ID 不是该列表中那些元素的唯一 ID。 I just need to add a few more properties from their "parent" table(B) in this new table.
我只需要在这个新表中从他们的“父”表(B)中添加更多的属性。 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.
C 的行数必须和 B 的行数相同。但是当我使用这个 SQL 查询时,结果表的行数甚至超过了 A 和 B 的总行数。我是使用 SQL 的初学者我将不胜感激任何帮助。
A basic JOIN
will do:一个基本的
JOIN
会做:
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您也可以将其与插入相结合,这样您就应该获得新表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.