0

我有两张表,第一张的结构部分概括了第二张的结构:

table1 (id, i, j, k, a, b, c, x, y, z) -- requests
table2 (id, a, b, c, d) -- essential elements / bank subjects

我需要从给定 ID插入table1记录。table2最好的方法是什么?

我有两个想法:

1:

DECLARE @a type, @b type, @c type
SELECT @a = a, @b = b, @c = c, FROM table2 WHERE id = @id
INSERT INTO table1 (i, j, k, a, b, c, x, y, z)
 VALUES (@i, @j, @k, @a, @b, @c, @x, @y, @z)

2:

CREATE TABLE #result (a type, b type, c type)
SELECT a, b, c INTO #result FROM table2 WHERE id = @id
INSERT INTO table1 (i, j, k, a, b, c, x, y, z)
  VALUES (@i, @j, @k,
    (SELECT a FROM #result),
    (SELECT b FROM #result),
    (SELECT c FROM #result),
    @x, @y, @z)

存在什么另一种方法?哪一个是最佳实践?

4

4 回答 4

6

我会这样做:

INSERT INTO table1 (i, j, k, a, b, c, d, x, y ,z)
Select  @i, @j @k, a, b, c, d, @x, @y, @z
From    table2
Where   id = @id

这使您免于将数据放入局部变量和/或临时表中。性能应该更好。

要实现的重要部分是您可以在选择中硬编码值。您列出列(插入行)的顺序必须与您在选择行中列出列的顺序相匹配。

于 2009-07-06T22:07:29.063 回答
2

您可以使用单个插入查询来完成:

insert into table1 (a, b, c, d, x, y, z)
select a, b, c, d, @x, @y, @z
from table2
where id = @id

编辑:
使用您添加的额外字段,它将是:

insert into table1 (i, j, k, a, b, c, x, y, z)
select @i, @j, @k, a, b, c, @x, @y, @z
from table2
where id = @id
于 2009-07-06T22:06:26.490 回答
1

The temp table could be a benefit through the development process if you are having trouble identifying what data are getting inserted. It could also be useful if you need to perform other data alterations that "require" a cursor to loop through the the records.

Otherwise, it is just another part of your code you would have to update when you add a field.

于 2009-07-07T01:37:35.423 回答
-2

您可以使用 MySQL GUI 工具,但我不知道是否可以这样做。 http://dev.mysql.com/downloads/gui-tools/5.0.html

于 2009-07-06T22:07:23.180 回答