使用匹配的密钥将数据从一个表填充到另一个表

时间:2013-06-17 14:57:33

标签: sql sql-server-2008 tsql

任何人都可以告诉我该怎么做....


    Table 1                                 Table 2
      Cat_ID   Cat_Name                        Term_ID     Term_Name
       1       ab                                 1986       January 2013
       2       cd                                 1987       February 2013
       3       ef                                 1988       March 2013
       4       gh

我希望输出为:


   Table 3 
    Term_ID     Term_Name          CAT_ID      CAT_Name
    1986       January 2013           1      ab
    1986       January 2013           2      cd
    1986       January 2013           3      ef
    1986       January 2013           4      gh
    1987       February 2013          1      ab
    1987       February 2013          2      cd
    1987       February 2013          3      ef
    1987       February 2013          4      gh
    1988       March 2013             1      ab
    1988       March 2013             2      cd
    1988       March 2013             3      ef
    1988       March 2013             4      gh

我必须把它写成SQL查询。

1 个答案:

答案 0 :(得分:5)

您可以使用CROSS JOIN获取所需的笛卡尔结果:

select t2.term_id, 
  t2.term_name, 
  t1.cat_id, 
  t1.cat_name
from table1 t1
cross join table2 t2

SQL Fiddle with Demo。获得结果后,您可以将数据插入table3

insert into table3 (term_id, term_name, cat_id, cat_name)
select t2.term_id, 
  t2.term_name, 
  t1.cat_id, 
  t1.cat_name
from table1 t1
cross join table2 t2