【问题标题】:Populate data from One table to another with out matching Key在没有匹配键的情况下将数据从一个表填充到另一个表
【发布时间】:2013-06-13 14:10:11
【问题描述】:

谁能告诉我怎么做....


    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 查询。

【问题讨论】:

标签: sql sql-server-2008 tsql


【解决方案1】:

您可以使用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

【讨论】:

  • 您好 Bluefeet,非常感谢您的回复。我想知道我们如何在编写大型查询时创建临时表并在同一个查询中使用它们。它是优化查询性能还是有更好的方法来使用大量视图编写大型查询
  • @snp.it 请使用“提问”按钮发布新问题,这样回答问题比通过 cmets 更容易。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-16
  • 2015-10-27
  • 1970-01-01
  • 2020-06-07
  • 1970-01-01
  • 2012-04-08
  • 1970-01-01
相关资源
最近更新 更多