加入两个没有公共ID的表

时间:2017-07-23 12:57:45

标签: sql sql-server

我有桌子周期:

CycleID   CycleName

1         2017   
2         2018
3         2019

表实体

EntityID  Entity   Description

1         Entity1
2         Entity2
3         Entity3

我需要循环生成第三个存储以下内容的表:

EntityID EntityDescription CycleID CycleName

1        Entity1           1       2017   
2        Entity2           1       2018
3        Entity3           1       2019
1        Entity1           1       2017   
2        Entity2           1       2018
3        Entity3           1       2019
1        Entity1           1       2017   
2        Entity2           1       2018
3        Entity3           1       2019

4 个答案:

答案 0 :(得分:2)

您似乎希望将表Cycle的每一行连接到表Entity的每一行。你需要一个笛卡尔联盟:

select e.entity_id,
    e.entity_description,
    c.cycle_id,
    c.cycle_name
from entity e
cross join cycle c

答案 1 :(得分:0)

一个简单的

 SELECT ... FROM entity,cycle 

会做(至少在mssql和oracle中)。

答案 2 :(得分:0)

DROP TABLE IF EXISTS `NewTable`;

CREATE TABLE `NewTable` (
`EntityID` int NOT NULL ,
`EntityDescription` varchar(255) NULL,
`CycleID` int NOT NULL ,
`CycleName` varchar(255) NULL
);

INSERT INTO `NewTable`
(EntityID, EntityDescription, CycleID, CycleName)
SELECT * FROM Cycle, entity

它适用于我的数据库。谢谢。

答案 3 :(得分:-1)

SELECT  Entity.EntityID,Entity.EntityDescription , Cycle.CycleID, Cycle.CycleName

FROM Entity CROSS JOIN Cycle;

在这个sql查询中,我们使用内连接加入2个表,连接条件是CycleID,EntityID应匹配。