简体   繁体   English

将另一个表的一部分插入到表中

[英]Insert into a table a part of another table

I have two tables, the structure of the first partially recapitulates, iterates the structure of the second: 我有两个表,第一个表的结构部分概述,第二个表的结构迭代:

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

I need to insert into table1 a record from table2 with given ID. 我需要将具有给定ID的table2的记录插入到table1 What is the best approach to do that? 最好的方法是什么?

I have two ideas: 我有两个想法:

1: 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: 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)

What another approach does exists? 存在另一种方法? Which one is the best-practice? 最佳做法是哪一种?

I would do it like this: 我会这样做:

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

This saves you from getting the data in to local variables and/or temp tables. 这样可以避免您将数据获取到局部变量和/或临时表中。 The performance should be better. 性能应该更好。

The important part to realize is that you can hard code values in the select. 要实现的重要部分是您可以在选择中硬编码值。 The order in which you list the columns (insert line) must match the order in which you list the columns in the select line. 列(插入行)的列出顺序必须与选择行中列的列出顺序匹配。

You can do it with a single insert query: 您可以使用单个插入查询来做到这一点:

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

Edit: 编辑:
With the extra fields that you added it would be: 使用您添加的额外字段,它将是:

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

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. 否则,这只是添加字段时必须更新的代码的另一部分。

You can use the MySQL GUI Tools, but I don't know if it's possible to do this. 您可以使用MySQL GUI工具,但我不知道是否可以这样做。 http://dev.mysql.com/downloads/gui-tools/5.0.html http://dev.mysql.com/downloads/gui-tools/5.0.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM