How to maintain subcategory in MYSQL? - sql

I am having categories as following,
Fun
Jokes
Comedy
Action
Movies
TV Shows
Now One video can have multiple categories or sub categories, let's say VideoId: 23 is present in Categories Fun, Fun->Comedy, Action->TV Shows but not in Action category. Now I am not getting idea that hwo should I maintain these categories in Database. Should I create only one column "CategoryId AS VARCHAR" in Videos and add category id as comma-separated values (1,3,4) like this but then how I will fetch the records if someone is browsing category Jokes?
Or should I create another table which will have videoId and categoryid, in that case if a Video is present in 3 different categories then 3 rows will be added to that new table
Please suggest some way of how to maintain categories for a particular record in the table
Thanks

You categories table could have a column in it called parentID that reference another entry in the categories table. It would be a foreign key to itself. NULL would represent a top-level category. Something other then NULL would represent "I am a child category of this category". You could assign a video to any category still, top-level, child, or somewhere inbetween.
Also, use autoincrement notnull integers for your primary keys, not varchar. It's a performance consideration.
To answer your comment:
3 tables: Videos, Categories, and Video_Category
Video_Category would have VideoID and CategoryID columns. The primary key would be a combination of the two columns (a compound primary key)

You have two choices, parentID (better as INT) to refer to the parent or an extra table with categoryID - parentID.
The last one may provide a better logical separation and allows you to have multiple categories.

I suggest that create another table which will have videoId and categoryid. Then you can use sql-query as follow:
select a.*,GROUP_CONCAT(b.category_id) as cagegory_ids
from table_video a
left join table_video_category b on a.video_id=b.video_id
group by a.video_id

Related

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.

Extending table with another table ... sort of

I have a DB about renting cars.
I created a CarModels table (ModelID as PK).
I want to create a second table with the same primary key as CarModels have.
This table only contains the number of times this Model was searched on my website.
So lets say you visit my website, you can check a list that contains common cars rented.
"Most popular Cars" table.
It's not about One-to-One relationship, that's for sure.
Is there any SQL code to connect two Primary keys together ?
select m.ModelID, m.Field1, m.Field2,
t.TimesSearched
from CarModels m
left outer join Table2 t on m.ModelID = t.ModelID
but why not simply add the field TimesSearched to table CarModels ?
Then you dont need another table
Easiest is to just use a new primary key on the new table with a foreign key to the CarModels table, like [CarModelID] INT NOT NULL. You can put an index and a unique constraint on the FK.
If you reeeealy want them to be the same, you can jump through a bunch of hoops that will make your life Hell, like creating the table from the CarModels table, then setting that field as the primary key, then whenever you add a new CarModel you'll have to create a trigger that will SET IDENTITY_INSERT ON so you can add the new one, and remember to SET IDENTITY_INSERT OFF when you're done.
Personally, I'd create a CarsSearched table that holds ThisUser selected ThisCarModel on ThisDate: then you can start doing some fun data analysis like [are some cars more popular in certain zip codes or certain times of year?], or [this company rents three cars every year in March, so I'll send them a coupon in January].
You are not extending anything (modifying the actual model of the table). You simply need to make INNER JOIN of the table linking with the primary keys being equal.
It could be outer join as it has been suggested but if it's 1:1 like you said ( the second table with have exact same keys - I assume all of them), inner will be enough as both tables would have the same set of same prim keys.
As a bonus, it will also produce fewer rows if you didn't match all keys as a nice reminder if you fail to match all PKs.
That being said, do you have a strong reason why not to keep the said number in the same table? You are basically modeling 1:1 relationship for 1 extra column (and small one too, by data type)
You could extend (now this is extending tables model) with the additional attribute of integer that keeps that number for you.
Later is preferred for simplicity and lower query times.

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.

Database Design Question - Categories / Subcategories

I have a question for how I would design a few tables in my database. I have a table to track Categories and one for Subcategories:
TABLE Category
CategoryID INT
Description NVARCHAR(500)
TABLE Subcategory
SubcategoryID INT
CategoryID INT
Description NVARCHAR(500)
A category might be something like Electronics, and its Subcategories might be DVD Players, Televisions, etc.
I have another table that is going to be referencing the Category/Subcategory. Does it need to reference the SubcategoryID?
TABLE Product
SubcategoryID INT -- should this be subcategory?
Is there a better way to do this or is this the right way? I'm not much of a database design guy. I'm using SQL Server 2008 R2 if that matters.
Your design is appropriate. I'm a database guy turned developer, so I can understand the inclination to have Category and SubCategory in one table, but you can never go wrong by KISS.
Unless extreme performance or infinite hierarchy is a requirement (I'm guessing not), you're good to go.
If being able to associate multiple subcategories with a product is a requirement, to #Mikael's point, you would need a set-up like this which creates a many-to-many relationship via a join/intersect table, Product_SubCategory:
CREATE TABLE Product (ProductID int, Description nvarchar(100))
CREATE TABLE Product_SubCategory (ProductID int, SubCategoryID int)
CREATE TABLE SubCategory (SubCategoryID int, CategoryID int, Description nvarchar(100))
CREATE TABLE Category (CategoryID int, Description nvarchar(100))
Hope that helps...
Eric Tarasoff
Having two separate tables for Categories and SubCategories depends on your situation.
If you keep it the way it is you are limited to a Category > Subcategory scenario, as in you can't have SubCategories of SubCategories.
If you make them into one table you need a column for ParentID. If a category is the top most it will have a ParentID of 0. If you want to allow unlimited sub categories foreach subcategory, e.g. Electronics > Recordable Media, Blueray, 4gb you will need to use recursive programming to display them.
Attach tags to the products in instead of a category hierarchy. It is much more flexible.
create table product (id, name,...)
create table tag (id, name, description)
create table product_tag (product_id, tag_id)
If categories and subcategories have the same attributes, then collapse them into one table.
If one 'sub' category can belong to more than one 'parent' category then add a link class, otherwise add a single column to point to a parent.
e.g. if you have Electronics > TV, can you also have Entertainment > TV ? etc.
Your other table should reference just the category_id (note - not parent_category_id)
hth
As long as Sub-Categories are never repeated in a different Category, and especially if they have different attributes, then your proposed method is good.
The one problem can come when you are adding/editing Products, and you don't have a field for Category, even though you probably want a control where the user can edit the Category.
It depends on your requirements. If every Product is linked to no more than one SubCategory you should have SubCategoryID in Products. There is no need to add CategoryID as well.
Other scenarios that require a different model might be that a Product could link directly to a Category instead of a SubCategory or that one Product could be linked to more than one SubCategory or that a SubCategory is linked to more than one Category.

How to display multiple values in a MySQL database?

I was wondering how can you display multiple values in a database for example, lets say you have a user who will fill out a form that asks them to type in what types of foods they like for example cookies, candy, apples, bread and so on.
How can I store it in the MySQL database under the same field called food?
How will the field food structure look like?
You may want to read the excellent Wikipedia article on database normalization.
You don't want to store multiple values in a single field. You want to do something like this:
form_responses
id
[whatever other fields your form has]
foods_liked
form_response_id
food_name
Where form_responses is the table containing things that are singular (like a person's name or address, or something where there aren't multiple values). foods_liked.form_response_id is a reference to the form_responses table, so the foods liked by the person who has response number six will have a value of six for the form_response_id field in foods_liked. You'll have one row in that table for each food liked by the person.
Edit: Others have suggested a three-table structure, which is certainly better if you are limiting your users to selecting foods from a predefined list. The three-table structure may be better in the case that you are allowing them the ability to enter their own foods, though if you go that route you'll want to be careful to normalize your input (trim whitespace, fix capitalization, etc.) so you don't end up with duplicate entries in that table.
normally, we do NOT work out like this. try to use a relation table.
Table 1: tbl_food
ID primary key, auto increment
FNAME varchar
Table 2: tbl_user
ID primary key, auto increment
USER varchar
Table 3: tbl_userfood
RID auto increment
USERID int
FOODID int
Use similar format to store your data, instead a chunk of data fitted into a field.
Querying in these tables are easier than parsing the chunk of data too.
Use normalization.
More specifically, create a table called users. Create another called foods. Then link the two tables together with a many-to-many table called users_to_foods referencing each others foreign keys.
One way to do it would be to serialize the food data in your programming language, and then store it in the food field. This would then allow you to query the database, get the serialized food data, and convert it back into a native data structure (probably an array in this case) in your programming language.
The problem with this approach is that you will be storing a lot of the same data over and over, e.g. if a lot of people like cookies, the string "cookies" will be stored over and over. Another problem is searching for everyone who likes one particular food. To do that, you would have to select the food data for each record, unserialize it, and see if the selected food is contained within. This is a very inefficient.
Instead you'll want to create 3 tables: a users table, a foods table, and a join table. The users and foods tables will contain one record for each user and food respectively. The join table will have two fields: user_id and food_id. For every food a user chooses as a favorite, it adds a record to the join table of the user's ID and the food ID.
As an example, to pull all the users who like a particular food with id FOOD_ID, your query would be:
SELECT users.id, users.name
FROM users, join_table
WHERE join_table.food_id = FOOD_ID
AND join_table.user_id = users.id;