简体   繁体   English

MYSQL:具有外键关系的多表插入

[英]MYSQL : multiple table insert with foreign key relationship

Orders table 订单表


order_id,  
parent_order_id,  
customer_id,  
payment_mode, 
price ,
shipping_price, 
billing_address_id,  
shipping_address_id,  
create_TS,  
update_TS 

Order Items 订购项目


order_id,
order_item_id, 
pos_code,  
quantity,  
unit_price, 
shipping_price, 
pickup_date,   
create_TS,   
update_TS,  
business_id,
item_id, 
delivery_id,  
workflow_id,

Order Adjustments Table 订单调整表


order_adjustment_id, 
order_item_id,  
offer_id,   
discount_value,  
create_ts, 
update_ts

When an order is placed, I insert data into these 3 tables plus a few other tables. 下订单后,我将数据插入这3个表以及其他一些表中。 All of them happen in a transaction. 所有这些都发生在交易中。 Currently the application uses JDBC to talk to the MYSQL DB. 当前,该应用程序使用JDBC与MYSQL DB进行通信。

The order of insertion is 1. Orders table. 插入顺序为1.订单表。 2. OrderItems table 3. Order_Adjustments table 2. OrderItems表3. Order_Adjustments表

The order id is a foreign key in the order items table and order item id is a foreign key in the order adjustments table. 订单ID是订单商品表中的外键,而订单商品ID是订单调整表中的外键。

When a customer places an order I divide the Parent order into sub orders based on the stores. 当客户下订单时,我会根据商店将父订单分为子订单。 For example if the cart contains item1 and item2 from store1 item3 and item4 from store2 例如,如果购物车包含来自store1的item1和item2和来自store2的item4

This single cart will be broken into 2 separate orders(due to logistics reasons) 单个购物车将分为2个单独的订单(由于物流原因)

So now the problem is, 所以现在的问题是

I need to know the corresponding order id for the order items table and similarly the corresponding order item ids for order adjustments table. 我需要知道订单项表的相应订单ID,以及订单调整表的类似订单项ID。

Because of which I am firing queries separately instead of a bulk insert. 因此,我分别触发查询而不是批量插入。 Is it even possible to acheive something like this using jdbc? 甚至有可能使用jdbc实现类似的功能吗?

You have to first fire query into 1. Orders table. 您必须首先将查询激发到1. Orders表中。

based upon it get MAX(order_id) from table Orders table , then use it for foreign key into other child tables. 基于它从表Orders表中获取MAX(order_id),然后将其用作其他子表的外键。

You can also get the id like this. 您也可以像这样获取ID。 It will return the id created by the DB for your order. 它将返回数据库为您的订单创建的ID。

p = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

After executeUpdate you can get the id like this. 在executeUpdate之后,您可以获得这样的ID。

ResultSet rs = p.getGeneratedKeys();
rs.getInt(1)

Now you can take the id and use it as a FK 现在您可以获取ID并将其用作FK

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

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