I am trying to create a table in my database using Visual Studio. I've got a table for my Products (like in online shop) and then I have a table for Orders, which should store all products that user has ordered. The problem is that I am not sure which datatype I should use when designing the database to store an array of products in my Orders table. This is what the Orders table should look like
-
1This is not what you want to do. You want to have two tables here. Orders and OrderLine.Sean Lange– Sean Lange2016-12-15 19:58:27 +00:00Commented Dec 15, 2016 at 19:58
-
Third table ProductionOrders will be your solutionTony Dong– Tony Dong2016-12-15 20:03:58 +00:00Commented Dec 15, 2016 at 20:03
-
Thank you. I considered using this method before but I took this example from a book and it never mentions creation of a third table. I will try doing it the way you suggested.Dave– Dave2016-12-15 20:08:27 +00:00Commented Dec 15, 2016 at 20:08
2 Answers
You should create Products and Orders table with relationship between them.
Your Orders table should have Id column as well (which is PrimaryKey)
Then you should create Products table, that keeps all the information about products and additionaly OrderId which should be used as Foreign Key to Orders table.
Please look at that link: https://msdn.microsoft.com/en-us/library/ms189049.aspx
It's also worth of checking:
One To One, One To Many, Many To Many relations in SQLServer to have better understanding and design your data store properly.
In your case you need ProductsOrders table, Many To Many relationship.
5 Comments
; separated string etc. It's not really approach you want to go. What's the book you are getting through?In Relational database, you can create a relationship between 2 tables.
The relationship can be
- 1 to 1 (1 Product - 1 Order)
- 1 to Many (1 Product - 'n' Order)
- Many to Many (n product - 'n' Order)
Based on your scenario, You can choose any of the relationship listed above. While querying from the database, you can easily operate over each order/Product.
