简体   繁体   English

SQL 插入到 2 个表中,将一个表中的新 PK 作为另一个表中的 FK

[英]SQL Insert into 2 tables, passing the new PK from one table as the FK in the other

How can I achieve an insert query on 2 tables that will insert the primary key set from one table as a foreign key into the second table.如何在 2 个表上实现插入查询,将一个表中的主键集作为外键插入到第二个表中。

Here's a quick example of what I'm trying to do, but I'd like this to be one query, perhaps a join.这是我正在尝试做的一个简单示例,但我希望这是一个查询,也许是一个连接。

INSERT INTO Table1 (col1, col2) VALUES ( val1, val2 )
INSERT INTO Table2 (foreign_key_column) VALUES (parimary_key_from_table1_insert)

I'd like this to be one join query.我希望这是一个连接查询。 I've made some attempts but I can't get this to work correctly.我做了一些尝试,但我无法让它正常工作。

This is not possible to do with a single query.这对于单个查询是不可能的。

The record in the PK table needs to be inserted before the new PK is known and can be used in the FK table, so at least two queries are required (though normally 3, as you need to retrieve the new PK value for use). PK表中的记录需要在新的PK已知并可以在FK表中使用之前插入,所以至少需要两次查询(虽然通常是3次,因为需要取回新的PK值才能使用)。

The exact syntax depends on the database being used, which you have not specified.确切的语法取决于您没有指定的正在使用的数据库。

If you need this set of inserts to be atomic, use transactions.如果您需要这组插入是原子的,请使用事务。

Despite what others have answered, this absolutely is possible, although it takes 2 queries made consecutively with the same connection (to maintain the session state).尽管其他人已经回答,但这绝对可能的,尽管需要使用相同的连接连续进行 2 次查询(以保持 session 状态)。

Here's the mysql solution (with executable test code below):下面是 mysql 解决方案(可执行测试代码如下):

INSERT INTO Table1 (col1, col2) VALUES ( val1, val2 );
INSERT INTO Table2 (foreign_key_column) VALUES (LAST_INSERT_ID());

Note: These should be executed using a single connection.注意:这些应该使用单个连接执行。

Here's the test code:这是测试代码:

create table tab1 (id int auto_increment primary key, note text);
create table tab2 (id int auto_increment primary key, tab2_id int references tab1, note text);
insert into tab1 values (null, 'row 1');
insert into tab2 values (null, LAST_INSERT_ID(), 'row 1');
select * from tab1;
select * from tab2;
mysql> select * from tab1;
+----+-------+
| id | note  |
+----+-------+
|  1 | row 1 |
+----+-------+
1 row in set (0.00 sec)

mysql> select * from tab2;
+----+---------+-------+
| id | tab2_id | note  |
+----+---------+-------+
|  1 |       1 | row 1 |
+----+---------+-------+
1 row in set (0.00 sec)

There may be a few ways to accomplish this.可能有几种方法可以做到这一点。 Probably the most straight forward is to use a stored procedure that accepts as input all the values you need for both tables, then inserts to the first, retrieves the PK, and inserts to the second.可能最直接的方法是使用一个存储过程,该过程接受两个表所需的所有值作为输入,然后插入第一个表,检索 PK,然后插入第二个表。

If your DB supports it, you can also tell the first INSERT to return a value:如果您的数据库支持它,您还可以告诉第一个 INSERT 返回一个值:

INSERT INTO table1... RETURNING primary_key; INSERT INTO table1... 返回主键;

This at least saves the SELECT step that would otherwise be necessary.这至少节省了原本需要的 SELECT 步骤。 If you go with a stored procedure approach, you'll probably want to incorporate this into that stored procedure.如果您使用存储过程方法 go,您可能希望将其合并到该存储过程中。

It could also possibly be done with a combination of views and triggers--if supported by your DB.如果您的数据库支持,它也可以通过视图和触发器的组合来完成。 This is probably far messier than it's worth, though.不过,这可能比它的价值要混乱得多。 I believe this could be done in PostgreSQL, but I'd still advise against it.我相信这可以在 PostgreSQL 中完成,但我仍然建议不要这样做。 You'll need a view that contains all of the columns represented by both table1 and table2 , then you need an ON INSERT DO INSTEAD trigger with three parts--the first part inserts to the new table, the second part retrieves the PK from the first table and updates the NEW result, and the third inserts to the second table.您需要一个包含table1table2表示的所有列的视图,然后您需要一个包含三个部分的ON INSERT DO INSTEAD触发器——第一部分插入新表,第二部分从第一个表并更新新结果,第三个插入到第二个表。 (Note: This view doesn't even have to reference the two literal tables, and would never be used for queries--it only has to contain columns with names/data types that match the real tables) (注意:这个视图甚至不必引用两个文字表,也永远不会用于查询——它只需要包含名称/数据类型与真实表匹配的列)

Of course all of these methods are just complicated ways of getting around the fact that you can't really do what you want with a single command.当然,所有这些方法都只是解决这样一个事实的复杂方法,即你不能用一个命令真正做你想做的事。

From your example, if the tuple (col1, col2) can be considered unique, then you could do:从您的示例中,如果元组 (col1, col2) 可以被认为是唯一的,那么您可以这样做:

INSERT INTO table1 (col1, col2) VALUES (val1, val2);
INSERT INTO table2 (foreign_key_column) VALUES (SELECT id FROM Table1 WHERE col1 = val1 AND col2 = val2);

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

相关问题 SQL查询从两个表中输出数据,这些表不是通过PK / FK直接链接,而是通过多个其他表链接? - SQL query to output data from two tables that are not directly linked by PK/FK, but are linked through multiple other tables? SQL 从第一个表中插入第二个表值,pk=fk 不起作用 - SQL Insert into second table values from first table with pk=fk not working sql从一个表中删除并比较数据另一个表都没有PK,FK关系 - sql deleat from one table with compare data another table both don't have PK,FK relation 从两个表中导入数据SQL + PK / FK - Import data from two tables SQL + PK/FK SQL从其他表插入新表 - SQL Insert from other table into new table 单个FK从多个表中引用PK - Single FK referes to PK from multiple tables 如何从另一个表插入并使用PK插入SQL Server中的多个表? - How to insert from another table and using PK to insert into multiple tables in SQL Server? SQL-表关系,主要是(PK / FK) - SQL - Table Relationships, Primarily (PK/FK) 在表中插入数据,在一个查询中用FK更新其他表 - Insert data in table, update other table with FK in one query 是否可以使用 select 查询从两个表中获取 PK 并将这些 PK 的值插入另一个将它们作为 FK 的表中? - Is it possibly to use a select query that gets the PK from two tables and inserts the values of those PK into another table that has them as FK?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM