[英]how to get Orders with its all products
I have question about order table design in MySQL. 我对MySQL中的订单表设计有疑问。 I have ORDERS table like 我有ORDERS表,例如
Order_id | Customer_id | Total_Price |
--------------------------------------
And on other side I have table PRODUCT 在另一边,我有桌子PRODUCT
Product_id | Product_name | available_amount
------------------------------------------
An order can contain several different Products. 一个订单可以包含几个不同的产品。 So,how can I change or update my database design like that I can efficiently access any Order with its all Products? 因此,如何更改或更新数据库设计,使我可以有效地访问所有产品的任何订单? Should I create seperate table names Order_details? 我应该创建单独的表名Order_details吗? Can you please help me? 你能帮我么?
Yep. 是的 You will want to create a separate table, like you mentioned, bringing together the Order and all of its Products, like so: 您将要创建一个单独的表(如您所述),将订单及其所有产品汇总在一起,如下所示:
Order_Product_id | Order_id | Product_id
----------------------------------------
1 | 1 | 1
2 | 1 | 3
3 | 1 | 5
4 | 2 | 3
5 | 3 | 1
6 | 3 | 2
Then you can get all the Products which are in an order like so: 然后,您可以按以下顺序获得所有产品:
Select op.Order_id, p.Product_id, p.Product_name
FROM Product p
JOIN Order_Product op ON op.Product_id = p.Product_id
WHERE op.Order_id = 1
you have an order which have multi products and product could be in one or many orders then you have many-to-many relationship. 如果您有一个包含多个产品的订单,并且产品可能处于一个或多个订单中,那么您将具有多对多关系。
you just need to add new table with this schema order_products(id, order_id, product_id) 您只需要使用此架构添加新表order_products(id,order_id,product_id)
Yes, the relation between orders and products are many to many, so you must break this relation by doing third table called order_products or order_details, this table has order_id, product_id as foreign keys. 是的,订单和产品之间的关系是多对多的,因此您必须通过创建名为order_products或order_details的第三个表来打破这种关系,该表具有order_id,product_id作为外键。 Also you should add quantity field, and sales_price field for this table. 另外,您应该为此表添加数量字段和sales_price字段。 Also you shouldn't put the total_price in orders table, but you can calculate the total by sum(quantity*sales_price) fields in the third table. 同样,您不应该将total_price放在订单表中,但是可以在第三个表中按sum(quantity * sales_price)字段计算总数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.