Design pattern - database many to many - sql

I have a question about many-tomany relationship. I know that we have to create a junction table. But let say we have this scenario:
one table for Customers
one table for Orders
one table for products
One order can have many products and one product might be in many orders. Therefore we create a junction table.
Could I just create a junction table between Customers and products and this junction would be a Order table to store the Orders?
Thanks

If you do that, how would you know which products a customer included on a specific order? And, how would you handle the customer ordering the same product on multiple orders?
So, no, you can't just create a Customer to Product junction table because that will not give you the information you ultimately need.

Related

Can i Create one table for purchases orders and sales orders?

I'm creating a Motorcycle store system, i wondering if i need to create one table that contains orders, the sales orders and the purchases orders with a column that will be called OrderType that determine if its purchase order or sale order
the same with Payments, money that i pay to supplier and money that customer pay to me, should be in table that called payment and column that determine if its outgoing payment or income
is that ok? or i need to create other tables
I would consider against it... Purchases are from a vendor YOU get the products from to build/fix/manufacture something.
Sales orders would have a customer you are selling to and thus would be foreign keys to different tables... unless your customer table has your vendors too and that has some column to identify difference as Vendor vs Customer.
Additionally, as you expand your design development and queries, purchasing history, etc., it may be more beneficial to have them separate.
You can create a single table. Whether this is good design or unfortunate design depends on how you use the data. How many times do you ever want to query these two datasets as if they were one dataset? How many times to you query them separately?

I am making a SQL database of categories and subcategories. What is the best way to link these tables?

The database has a table called "categories" with columns CATEGORY_ID(primary key) and CATEGORY_NAME.
I have subcategories for each category.
For better accessing which is the best method from the below methods.
Method 1: The "CATEGORY_ID" column in the "categories" table is a FOREIGN KEY in the "subcategories " table.
Method 2: Maintaining a separate table for each category representing the subcategories.
I prefer to use same table for category and sub category
like
Table Categories
[CATEGORY_ID, CATEGORY_NAME, PARENT_CATEGORY_ID]
In case you don't know how many sub categories are there.
This scenario is just an example, the scenario is as follows: We have a product table where all the records of products are stored. Same way we will have customer table where records of customers are stored. The daily sales keep the record of all the sales. This sales table will keep record of which product who has purchased. So linking is to be done from Sales table to product table and customer table.
The query to link the two tables is as follows:SELECT product_name, customer.name, date_of_sale FROM sales, product, customer WHERE product.product_id = sales.product_id and customer.customer_id >= sales.customer_id LIMIT 0, 30
It is better to go with Method 1 since it is more scalable.
Let me elaborate on this. If we go with method 1, we need to maintain 2 tables only that is Categories and Subcategories. In future if we have new categories or subcategories we can directly deal with this 2 tables.
If we consider same situation with Method2 then we need to create new tables every time, this may become maintenance overhead.
Let me be a bit more direct. You explain in a comment that Method 2 is a separate table for each category. If so, then Method 2 -- in general -- is just wrong.
There are two methods for storing this type of information. One is a Categories table with a (single) Subcategories table. The Subcategories table would have CategoryId, a foreign key reference back to Categories. This is the normalized data model.
The second method is to store everything in one table. Each row would be a category/subcategory combination. Information about a given category would be duplicated across multiple rows, so this is not a normalized approach. However, this is a typical approach when doing dimensional modeling for decision support systems.
If the subcategories are just names of things, there is a third approach, which would be to store a list of the subcategories within each Category row. The list would not be a delimited string. It would be JSON, a nested table, XML, array, or similar collection data type supported by the database you are using. I am mentioning this as a possibility, but not recommending it.

Improvement on database schema

I'm creating a small pet shop database for a project
The database needs to have a list of products by supplier that can be grouped by pet type or product category.
Each in store sale and customer order can have multiple products per order and an employee attached to them the customer order must be have a customer and employee must have a position,
http://imgur.com/2Mi7EIU
Here are some random thoughts
I often separate addresses from the thing that has an address. You could make 1-many relationships between Employee, Customer and Supplier to an address table. That would allow you to have different types of addresses per entity, and to change addresses without touching the original table.
If it is possible for prices to change for an item, you would need to account for that somehow. Ideas there are create a pricing table, or to capture the price on the sales item table.
I don't like the way you handle the sales item table. the different foreign keys based on the type of the transaction is not quite correct. An alternative would be to replace SalesItem SaleID and OrderId with the SalesRecordId... another better option would be to just merge the fields from InStoreSale, SalesRecord, and CustomerOrders into a single table and slap an indicator on the table to indicate which type of transaction it was.
You would probably try to be consistent with plurality on your tables. For example, CustomerOrders vs. CustomerOrder.
Putting PositionPay on the EmployeePosition table seems off to... Employees in the same position typically can have different pay.
Is the PetType structured with enough complexity? Can't you have items that apply to more than one pet type? For example, a fishtank can be used for fish or lizards? If so, you will need a many-to-many join table there.
Hope this helps!

How to stablish a one to many relationship between 2 tables

I'm dealing with this situation. I've got three tables in SQL SERVER called Movies, Series and Orders.
Orders has an ItemId where this could be a MovieId (Movies PK) or SerieId (Series PK). I mean, in Orders table could have records where are from movies of series.
I don't know how to maintain this relationship or which could be the best way to implement it. Until I know, I only can create 1 to 1 or 1 to many relationships between 2 tables, not for 3.
Thanks in advance.
In this case I think it would be better to store Movies and Series in the same table with the common attributes incl. a column which indicates the type (Movie or Serie) and then have the additional attributes in seperate tables (if you want to normalize) or even in the same table (in order to avoid joins).
You should learn about implement table inheritance in sql-server.
Do you have a product and this product may be a Movie or a Serie.
In linked sample a person may be a student or a teacher.
The best way is:
create a generic table for movies and series with the fields that both entities should share (like ItemId).
create a table for movies that references the table created on step 1, containing the fields that must be compiled only for movies. This new table will be in relation one-to-one with the previous one.
same thing for series.
create the orders table and set ItemId foreign key to point to the ItemId primary key of the table created on step 1.

How do I tie a table to a value (for example an ID) in SQL?

These are actually two questions relating to an online bookstore.
I have a table for customers in SQL, and it has all this customer info, including a customer ID. Then I have a table full of books on sale. Lastly, I have a table for a shopping cart.
Now the shopping cart is going to be a table very similar to the books table, only it will have less items since it'll contain some subset of the book table's contents.
I want the entire cart to be tied to a single customer's ID, and I want every entry in that cart to come directly from the Books table.
How to I go about defining such a table, I mean what statements do I need?
As it is, I'm confused about the issue, because the entire cart table essentially an attribute of a single customer, but I have no idea how to represent that in SQL. I want to be able to look up the cart table using the customer ID, basically.
Any help would be greatly appreciated.
You basically need these four tables:
create table books (book_id int, name varchar(200), author(200));
create table customers (customer_id int, name varchar(200));
create table carts (cart_id int, customer_id int);
create table cart_details (cart_id int, line_number int, book_id int, qty int, price numeric(18,2));
In essence, you will store objects like this:
Books into books table
Customers into customers table
Carts into carts and cart_details table. carts will represent a cart for a certain customer, and cart_details will represent cart's content.
Whenever you want to retrieve a cart corresponding to a certain customer you can just do:
select * from carts inner join customers using (customer_id);
If you also want cart's detail you can do:
select * from carts
inner join cart_details using (cart_id)
inner join customers using (customer_id)
;
Note: Tried to write examples in a as general as possible SQL syntax since you didn't provide the RDBMS you are using. Also, left out on purpose all details related to primary and foreign keys so you can understand tables and their attributes first.
You could address this by creating a CustomerCart table that references the Customer and Book tables. It could have a format like the following (I'm making this as non-implementation-specific as possible, partly because you haven't indicated what RDBMS you're using):
Composite primary key consisting of CustomerId + a CartId (allows a Customer to have multiple / saved / historical carts)
BookId (each record then represents an instance of a book from the catalog being added to a customer's cart)
Measures, such as Quantity, that relate to the instance of the given book in the given customer's cart
Think of your problem like this... one customer can have many books in their shopping cart, and one book can exist in many customers' shopping carts, so you have a many-to-many relationship.
With this in mind, the way to handle this problem is create a table that tracks the associations between customers and books, including any other information that is relevant.
create table shopping_cart (
customerId int,
bookId int,
quantity int,
etc...
)
It depends on the functionality you want to support with a cart.
The easiest would be to create a cart table with BookID and CustomerID. However if a customer or book is ever removed; you will, though cascade deletes if allowed, automatically remove something from someone's cart... or remove all their cart items for a person if the person is removed... do you want that to happen? If not then you need to keep all book and customer information in the cart.
Secondly, do you want to keep record of everything they've purchased over time in a "Cart" do you want them to be able to checkout with a subset of items in their cart? Is the life of the cart their visit to the site, or would the items remain months/years after they come back?
The answers to these types of questions determine the appropriate design.