product_id
从product_shirt
和中删除字段product_ring
,并将它们的id
字段作为主键和外键product.id
。
您的order_item
表将包含一个外键到product.id
.
当您需要按给定顺序提取有关产品的信息时,请product
仅使用 JOIN 进行查询。当您需要特定产品的完整详细信息时,也可以根据实际产品类型加入product_shirt
或加入。product_ring
例子:
-- red XL shirt: product #1
INSERT INTO product VALUE (1, 'Red XL shirt', 'What a lovely shirt');
INSERT INTO product_shirt VALUE (1, 'XL', 'red', 1, 12);
-- blue S shirt: product #2
INSERT INTO product VALUE (2, 'Blue S shirt', 'How nice a shirt');
INSERT INTO product_shirt VALUE (2, 'S', 'blue', 1, 12);
-- small ring: product #3
INSERT INTO product VALUE (3, 'Small ring', 'One to rule them all');
INSERT INTO product_ring VALUE (3, 'S', 1, 5);
-- customer orders a "Blue S shirt" and a "Small ring":
INSERT INTO order_item VALUES (
1, -- order_number
2, -- product_id
1, -- quantity
), (
1, -- order_number
3, -- product_id
1, -- quantity
);
-- overview of the basket
SELECT * FROM order_item
JOIN product ON product.id = order_item.product_id
WHERE order_number = 1;
-- details of the basket contents
-- -- this will only show details pertaining to products of type "shirt", if any
SELECT * FROM order_item
JOIN product ON product.id = order_item.product_id
JOIN product_shirt ON product_shirt.id = product.id
WHERE order_number = 1;
-- -- this will only show details pertaining to products of type "ring", if any
SELECT * FROM order_item
JOIN product ON product.id = order_item.product_id
JOIN product_ring ON product_ring.id = product.id
WHERE order_number = 1;
-- notice you cannot UNION these results as we expect a different number of columns
-- your application classes are expected to handle these differences