[英]two columns primary key, auto-increment and foreign key
以下查詢成功完成,但是當我在訂單ID中輸入空值,並在商品ID中輸入不同的值(列中不存在的值)時,訂單ID仍在遞增。 如何保留相同的訂單ID? 外鍵的聲明方式是否有問題?
CREATE TABLE orders(
orderid int not null auto_increment,
itemid int not null,
quantity int not null,
tot_price int not null,
cid int not null,
code varchar(10),
order_time time,
order_date date ,
constraint order_pk primary key (orderid, itemid),
foreign key (itemid) references items(itemid),
foreign key (cid) references customer(cid),
foreign key (code) references coupon(code)
);
問題源於試圖在單個表中進行一對多(訂單到商品)關系。 這將嚴重結束。 你需要兩個。 一個用於訂單,一個用於訂單中的項目。 無論好壞,這都是關系數據庫執行列表的方式。
CREATE TABLE orders (
orderid int not null primary key auto_increment,
cid int not null references customer(cid),
code varchar(10) references coupon(code),
when_ordered datetime,
INDEX(when_ordered)
);
CREATE TABLE items_in_an_order (
orderid int not null references orders(id),
itemid int not null references items(id),
quantity int not null,
price_paid int not null
);
quantity
移動到items_in_an_order
。 我將total_price
更改為更具描述性的price_paid
,這可能對您要存儲的內容更具描述性。 這將使您出示收據。
order_date
和order_time
不必要地分為兩列。 這使得比較和排序很尷尬。 將它們放在一起放在一個DATETIME列中並對其建立索引,即可按日期/時間進行排序,並檢查訂單是否在日期/時間范圍內。
要獲得訂單中的所有項目, 請執行join 。
SELECT items.itemid
FROM items
JOIN items_in_an_order io ON io.itemid = items.id
WHERE io.orderid = ?
要查找某項所處的所有訂單,還可以進行聯接。
SELECT orders.id
FROM orders
JOIN items_in_an_order io ON io.orderid = orders.id
WHERE io.itemid = ?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.