从已连接的表创建表

时间:2018-06-11 14:54:50

标签: sql

我不知道这个问题是否适合这里。

所以我已经用表Y中的值创建了一个表X. 现在我必须只获取表X中的值,并从表Y中继续连接更多值并创建表Z.

Table X 
ID   Car   Color
1     BMW   Red
1     Ford   Blue
2     VW     Black

Table Y
ID  Car  Color Height Weight
1   BMW   Red   2      1000
1   Ford  Blue  4      1500
1   Tesla Green 3       850
1....

我尝试使用内部联接ID,但现在我从表Y中获取所有ID,而不仅仅是表X中的ID。

ID  CAR  Color Height  Weight
   1   BMW   Red   2      1000
   1   Ford  Blue  4      1500
   1   Tesla Green 3       850

但我需要得到这个:

ID  Car  Color Height Weight
1   BMW   Red   2      1000
1   Ford  Blue  4      1500

我知道我可以使用表格X并离开加入值,但是有更“清洁”,更快的方式吗?我认为可以通过内连接完成,但它不起作用。 或者我必须在ID上,车上,颜色上进行内连接? 我希望这个问题是可以理解的。

create table tableZ AS 
select tx.ID, ty.CAR,ty.Height,ty.Weight
from .... ty 
INNER JOIN ... tx on (tx.ID = ty.ID)

1 个答案:

答案 0 :(得分:0)

对于不是表格唯一ID的列,

ID是一个非常糟糕的名称。无论如何,你显然想要加入身份证,汽车和颜色,所以这样做:

create table tableZ AS 
select tx.ID, ty.CAR, ty.Height, ty.Weight
from ty 
INNER JOIN tx on tx.ID = ty.ID and tx.car = ty.car and tx.color = ty.color;

(如果您单独加入id,则将每个tx行与同一id的每个第9行合并。)