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

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.

Related

Terminology am I doing a one to many or many to many? Left join? Right?

I need to research this but am confused about the terminology of what I should be researching.
Table1 fields:
salenumber
category
quantity
price
Table2 fields:
field
category
requirement
Table3 fields:
field
salenumber
value
I need to combine these.
Essentially one (salenumber, category, quantity, Price) can have a dynamic number of "fields" containing unique "data associated with it. I'm a little confused as to the terminology of what I am doing here. I'm all mixed up with left and right joins and many to one and many to many databases. If I simply knew the term for what I am trying to do it would help me to narrow down my research.
Joins are for your queries - which you run to find specific records from your database. You aren't there yet. First, you want to do table design, which is where you consider many-to-many and one-to-many relationships.
Start by thinking about what the tables represent. For example, a single sale can involve multiple different products (e.g. you buy a fork, a spoon, a knife, and a new car). Each product can be in a different category (utensils or motor vehicles, in this case). In your table design, you would decide whether a product belongs to only a single category or to multiple categories.
Let's assume there's just one category per product - then you can have many products in one category (fork, spoon and knife are all utensils), but a product can have only one category. In this case, Category to Product is a One-to-Many relationship.
How these connect is where the related fields in tables come in to play - so in the Product table you have 'Category', which refers to the Category table ('Fork' is of Category 'Utensil', and in the Category table 'Utensil' is an entry with additional information).
You probably want to look up some basic database lessons to help you out. There are some good free online classes and resources - just search for info about databases.
This may help understand joins: http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/
If you have a row in Table_A with some id, and multiple rows in Table_B related referencing that id you can do a LEFT OUTER JOIN (often just LEFT JOIN). This will match the data in Table_A to Table_B - but you will have as many rows as there were in Table_B!
If you want all of the Table_B data related to the Table_A row in one row result you need an aggregate function. In SQL this is normally something like array_agg. When you do this you need to tell it what to GROUP BY, in my example it would be Table_A.id

Whats kind of relationship should I create ? One-To-One or One-To-Many?

I am using MS-Access database.
I am trying to make relationship with two tables, Old Customer table having data and Newly added coupon table.
As my client want to introduce new concept of coupon, where customer come with coupon instead of giving cash.
I have inserted Coupon code in coupon table in bulk.
Now, I am confused about what kind of relationship I should create with these two tables ?
I have to consider the below things...
customer can give either cash or coupon.
IF customer show the coupon, there will be an entry in CouponID column
as well in cash column (to know the value of that coupon.)
The CouponID should be unique in the customer table, Coupon Code should
not be repeated.
I am confused whether it should be one-To-One or One-To-Many ?
This image will help you to understand the problem.
I would not include "CouponID" in the customer table at all (nor "Cash" for that matter). The customer table models a customer, the coupon table models a coupon.
You need another table to model the transaction:
[CustomerTransaction]
id
date
customer_id
coupon_id
etc...
Every type of independent "thing" should be modeled by a discrete table. and "things" should be related to each other by other tables that create the 1:N relationship.
The relationship of customer to coupon is an optional (ie nullable) one-to-one; your data model looks good.
Some other comments:
The table would be better named sale rather than customer, since if the same customer comes back again, there will be a new row (but with the same name)
You could create a unique index on couponID that ignores nulls
You could rename Cash to Amount; the amount is either "cash" or coupon - the couponID column tells you the type of the amount
To create a unique index that ignores nulls:
CREATE UNIQUE INDEX idx1 ON customer (couponID) WITH IGNORE NULL;

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!

Design pattern - database many to many

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.

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.