[英]MySQL - Inserting Primary Key from one table to another (Foreign Key)
Although this question has been asked, It hasn't really adapted to how I wanted it to work for me, as i keep receiving errors. 虽然这个问题已被提出,但它并没有真正适应我希望它如何为我工作,因为我一直收到错误。
I have a table: Customer_orders which i insert values into: 我有一个表:Customer_orders我将值插入:
<sql:update var="count">
insert into customer_order (order_date,delivered ,shipping_date,customer_number )
values ( SUBDATE(NOW(), INTERVAL 17 DAY), 1, SUBDATE(NOW(), INTERVAL 14 DAY), <%= session.getAttribute( "username" ) %> );
</sql:update>
Now this customer_order has PRIMARY KEY called "Order Number" that auto increments 现在这个customer_order有一个名为“Order Number”的PRIMARY KEY,它自动递增
I want to take this order_number and insert it into a table, I tried something like: 我想取这个order_number并将其插入表中,我尝试了类似的东西:
<sql:update var="count">
insert into order_item (item_code,value,order_number,quantity)
values( "<%= request.getParameter( "item_code" ) %>", "<%= request.getParameter( "item_price" ) %>",customer_order(order_number),1 );
</sql:update>
And i even tried different ways to insert the order_number but I can't get it to work. 我甚至尝试了不同的方式来插入order_number但我无法让它工作。 When I created the two tables, the order_number is a foreign key in the 2nd table so I thought it would grab the value itself but didn't.
当我创建两个表时,order_number是第二个表中的外键,所以我认为它会抓取值本身但不会。
What am i doing wrong? 我究竟做错了什么?
you can simply get the last inserted id from your first query in a transaction and then insert it in another table as you like , so for that i propose this approach it may help you : 你可以简单地从事务中的第一个查询中获取最后一个插入的id,然后根据需要将其插入另一个表中,所以我建议这种方法可以帮助你:
<sql:transaction dataSource="${snapshot}" >
<sql:update var="count">
insert into customer_order (order_date,delivered ,shipping_date,customer_number )
values ( SUBDATE(NOW(), INTERVAL 17 DAY), 1, SUBDATE(NOW(), INTERVAL 14 DAY), <%= session.getAttribute( "username" ) %> );
</sql:update>
<sql:query var="las_inserted_id" >
SELECT LAST_INSERT_ID() as last_Id
</sql:query >
/*now you got the last inserted id so that you can simply insert it in your new query as you like*/
<sql:update var="count">
insert into order_item (item_code,value,order_number,quantity)
values( "<%= request.getParameter( "item_code" ) %>", "<%= request.getParameter( "item_price" ) %>",${ las_inserted_id.rows[0].last_Id },1 );
</sql:update>
</sql:transaction>
NB : please try as much as you can to avoid sql logic code in your view !! 注意 :请尽可能多地尝试避免在您的视图中使用sql逻辑代码! so that it could be easy to maintain your application
这样可以很容易地维护您的应用程序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.