如何基于另外两个表创建表?

时间:2019-07-13 09:41:59

标签: sql sql-server tsql

所以我有两个表,想象一下:

  • 表1:

    +------+
    | Name |
    +------+
    | John |
    | Mary |
    | Pete |
    +------+
    
  • 表2:

    +--------+
    |  City  |
    +--------+
    | Paris  |
    | London |
    +--------+
    

我想要第三个表,其中包含这两个表之间的所有情况:

+--------+---------+
|  City  |   Name  |
+--------+---------+
| Paris  |  John   |
| Paris  |  Mary   |
| Paris  |  Peter  |
| London |  John   |
| London |  Mary   |
| London |  Peter  |
+--------+---------+

是否可以这样做?我无法使用联接来实现,因为它们之间没有任何关联。

3 个答案:

答案 0 :(得分:1)

是的,有可能。请在下面的SQL QUERY中使用。

这是SQL:

create table table3 AS
select table1.Name,table2.City from table1 
join table2;

我希望使用上述SQL可以解决您的问题。

答案 1 :(得分:1)

  

我无法通过联接执行此操作,因为它们之间没有任何关联。

您实际上可以使用join来做到这一点:

select c.city, n.name
from table2 c join
     table1 n
     on 1 = 1;

on子句中的条件几乎可以是任何东西。

但是,笛卡尔积-您想要做的-是理解联接的基础。因此,SQL直接支持它们:

select c.city, n.name
into table3
from table2 c cross join
     table1 n;

实际上,将其写为显式join并不像听起来那样疯狂。如果任何一个表为空,则cross join不返回任何行。有时,您想在其他表中保留行。外连接解决了这个问题:

select c.city, n.name
into table3
from table2 c full join
     table1 n
     on 1 = 1;

答案 2 :(得分:0)

如果要创建第三个表,则

使用此:

  Select * into Table3 from ( select City, Name from Name cross join City  ) as Tab

  GO

否则,您可以为它创建一个view

 Create View NameCity 
 As
 select City, Name from Name cross join City

 GO
相关问题