簡體   English   中英

MySQL - 將主鍵從一個表插入另一個表(外鍵)

[英]MySQL - Inserting Primary Key from one table to another (Foreign Key)

雖然這個問題已被提出,但它並沒有真正適應我希望它如何為我工作,因為我一直收到錯誤。

我有一個表: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> 

現在這個customer_order有一個名為“Order Number”的PRIMARY KEY,它自動遞增

我想取這個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>

我甚至嘗試了不同的方式來插入order_number但我無法讓它工作。 當我創建兩個表時,order_number是第二個表中的外鍵,所以我認為它會抓取值本身但不會。

我究竟做錯了什么?

你可以簡單地從事務中的第一個查詢中獲取最后一個插入的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>

注意 :請盡可能多地嘗試避免在您的視圖中使用sql邏輯代碼! 這樣可以很容易地維護您的應用程序

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM