从2个表SQL Server中选择和插入的更优雅方式

时间:2011-02-18 00:14:31

标签: sql tsql sql-server-2008

我有2个表,如:

ID NAME
-------------
1  someValue
2  someValue
3  someValue
4  someValue
...


ID NAME
-------------
1  var
2  var2
3  var3
4  var4
...

我想在table1中插入@table 2个结果,并且从table2获得3个不同ID的结果,目前我有类似的内容:

Declare @vars TABLE(
        field1  varchar(80),
        field2  varchar(80),
        field3  varchar(80),
        field4  varchar(80),
        field5  varchar(80)
    )

INSERT INTO @vars(field1, field2, field3, field4, field5)
    SELECT  a.Name,
            b.Name,
            c.Name,
            d.Name,
            e.Name
    FROM    @Table1  a,
            @Table1  b, 
            @Table2  c,
            @Table2  d,
            @Table2  e
    WHERE   a.ID = 1 
    AND     b.ID = 25
    AND     c.ID = 12 
    AND     d.ID = 25 
    AND     e.ID = 14 

我得到了预期的值,但是......

  • 有更优雅的方式吗? 这个?我想我做的不仅仅是 需要的。

Pd积。 我得到类似的东西:

field1  field2 field3 field4 field5
-------------------------------------
val1     var2    val4   val7   var7

2 个答案:

答案 0 :(得分:4)

如果ID是表1和表2中的主键或唯一键,则可以改为执行此操作。

insert into @vars
select
  (select Name from @Table1 where ID = 1),
  (select Name from @Table1 where ID = 25),
  (select Name from @Table2 where ID = 12),
  (select Name from @Table2 where ID = 25),
  (select Name from @Table2 where ID = 14)

答案 1 :(得分:1)

我不确定它是否更优雅,但这是一个不同的查询也是如此。

WITH myTables AS
    ( SELECT ID, NAME, 'Table1' AS SOURCE
    FROM Table1

    UNION ALL

    SELECT ID, NAME, 'Table2' AS SOURCE
    FROM Table2
    )
INSERT INTO @vars(field1, field2, field3, field4, field5)
SELECT MAX(CASE WHEN source = 'Table1' AND id = 1  THEN NAME END) AS field1,
    MAX(CASE    WHEN source = 'Table1' AND id = 25 THEN NAME END) AS field2,
    MAX(CASE    WHEN source = 'Table2' AND id = 12 THEN NAME END) AS field3,
    MAX(CASE    WHEN source = 'Table2' AND id = 25 THEN NAME END) AS field4,
    MAX(CASE    WHEN source = 'Table2' AND id = 14 THEN NAME END) AS field5
FROM myTables
WHERE SOURCE = ('Table1'  AND ID IN (1, 25))
    OR (SOURCE = 'Table2' AND ID IN (12, 25, 14)) ;

它使用公用表表达式(CTE)来创建两个表的并集。它还使用MAX聚合来转动数据。您也可以使用PIVOT运算符执行此操作。