![](/img/trans.png)
[英]mysql insert into two tables using auto_increment value from the first table as a foreign key in the second
[英]MYSQL auto_increment insert statement from two foreign keys
. 我正在為我大學的最后一年項目制作一個數據庫,但我目前陷入困境。 我有三個表: product
、 customer
和product_order
。
product
有一個 auto_incremented 主鍵product_ID
並且customer
也有一個 auto_incremented 主鍵customer_ID
。
product_order
表是我的問題所在(我知道 mysql 不支持 @insert 和 @scope_identity,@last_insert_id 對我也不起作用)
我在這里有兩個來自產品和客戶表的外鍵(它們是 auto_increment ids 並使用我在網上看到的變量
SELECT @last := LAST_INSERT_ID();
只返回 product_ID 和 customer_ID 中的最后一個 id。
我有這些插入語句:
insert into Product values(1000 ,'Logitech Webcam C270 HD mic USB', 260, 5, 'Accessory');
insert into customer VALUES(2000, 'Rachel ' , 'Mc Roy' , 'Rach@gmail.com', 'female','1985/06/05','wlovely8', '41, Cantubury Lane, San Franscique', 2938493);
insert into product_order values(@last_id_in_Customer, @last_id_in_Product, 'Logitech Webcam C270 HD mic USB', 260, 1);
我正在插入 id 以設置我希望 id 落入的范圍; 這就是我放 2000 和 1000 的原因; 在其他插入中,我利用 null 自動將數據插入表中
select * from product_order;
2001 2001 Logitech Webcam C270 HD mic USB 260 1
我的查詢輸出只能插入一次,因為 @last 變量只返回一次。
所以我的問題是:有沒有更好的方法來做到這一點?
順便說一句,這是用於客戶登錄網頁,因此客戶不必輸入唯一的主鍵。
是的,有一個更好的方法來做到這一點假設當客戶注冊時,他將獲得 customer_id 自動遞增,當客戶登錄系統時,將其存儲在會話變量中,每當他選擇任何產品時,從會話中檢索 customer_id 並從中檢索 product_id產品表並將其添加到 order_product 表中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.