0

以下查詢已成功完成,但是當我將空值輸入到訂單標識和項目標識的不同值(列中不存在的那些值)時,訂單標識仍爲越來越多。如何保留相同的訂單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) 
); 
+2

您需要更好地標準化。你應該有第三個包含你的訂單項目的表格,否則你會在每一行重複很多不必要的值。 –

+0

你正在使用哪種引擎類型? –

+0

作爲一個附註,在不同的字段中有order_time和order_date是奇數。單個[DATETIME字段](https://dev.mysql.com/doc/refman/5.6/en/datetime.html)如何?這將使得範圍計算變得更簡單。索引會使事情變得更快。 – Schwern

回答

0

該問題源於嘗試在單個表中執行一對多(訂單到物料)關係。這將會嚴重結束。你需要兩個。一個用於訂單,一個用於訂單中的物品。無論好壞,這都是關係數據庫如何執行列表。

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_dateorder_time被不必要地分成兩列。這使得比較和排序很尷尬。將它們放在一個DATETIME列中並編制索引可讓您按日期/時間進行排序,並檢查訂單是否在日期/時間範圍內。

要獲得訂單中的所有項目,do a 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 = ?