SQL查询:为每个项添加多个值

时间:2016-10-06 19:08:10

标签: mysql sql sql-server oracle informix

如何编写SQl查询以使用Table1和Table2创建“NewTable”,结果看起来像下面的“NewTable”?

   Table1   
 EmmployeeID
|     1     |
|     2     |
|     3     |

  Table2
 AgencyID
|   a    |
|   b    |
|   c    |

              NewTable
      |EmmployeeID|AgencyID|
      |     1     |   a    |
      |     1     |   b    |
      |     1     |   c    |
      |     2     |   a    |
      |     2     |   b    |
      |     2     |   c    |
      |     3     |   a    |
      |     3     |   b    |
      |     3     |   c    |     

4 个答案:

答案 0 :(得分:1)

组合两个表通常意味着JOIN

生成行的每个可能组合("配对")通常意味着"笛卡尔积",也称为CROSS JOIN,如下所示:

select EmployeeID, AgencyID
from Table1 CROSS JOIN Table2

答案 1 :(得分:1)

尝试使用

CREATE TABLE NewTable
select EmmployeeID,AgencyID 
from Table1,Table2

答案 2 :(得分:1)

通过执行INSERT CROSS JOINTable1

创建第三个表格然后Table2
CREATE TABLE NewTable
( 
  EmployeeID int,
  AgencyID varchar,
);

INSERT INTO NewTable
select EmployeeID, AgencyID
from Table1 CROSS JOIN Table2

答案 3 :(得分:0)

使用CROSS APPLYCROSS JOIN。例如,

declare @a table (a int)
declare @b table (b char(1))

insert @a values (1),(2)
insert @b values ('a'),('b')

select * from @a cross apply @b order by a