Need help setting up Foreign Key relationship in MySQL DB - mysql

So I have to InnoDB tables (Products) and (Categories). I wanted to setup a relationship between the "Category" field on the Products table, and the "CategoryId" of the Categories table.
But when attempting to create a FK it will only let me select the Primary Key "ProductsId" on the Products table and map to the PK "CategoryId" on the Categories table.
Maybe I am missing the way/reason to setup a Foreign key. My thoughts and tell me if I am wrong:
1) Was to require a product be added to a category when added, the category must exist or you must create it first. You can't remove a category unless you perform some task (programmically or on the DB backend) to remove the products from a category you are wanting to remove.
2) I was expecting the CategoryId value to be stored in the "Category" field of the Products table. Then when displaying in my view, would need to look up the Categories.Name field by the CategoriesId value.
EDIT:
So I understand that two fields involved in the Foreign keys must be the same, size, types...etc. However, how does linking up the ProductId and CategoryId work in context to what I mentioned above I am wanting to do. When I did create a FK between ProductId and CategoryId, I won't let me add a product record.
Also, the Category Name field and the Product Category field are the same type, size..etc, yet I don't get the option to select those in the foreign key tab?
How should I be setting it up so that the categories table will know what products are part of each category.

Ok, unfortunately, I must answer my own questions. The reason for most of my technical problems is because the field you are trying to make "must be indexed".
The comprehesive issue I was having was that I needed to get rid of the actual "Category" varchar field on the Products table, and create a CategoryId field that would have only a value that exists in the Category table CategoryId field.
Now I will just have to reference the Categories.Name field through the Products.CategoryId value.
At least this is what I have come to understand.

If you're on the Workbench, verify that the types, lengths and attributes of both columns involved in the FK are the same.

Related

Creating unique url for products and categories in mysql

I am creating a database for a website.
I am facing a problem and it is that I am not sure how to combine tables to not have the same url on a product or category.
My idea is to create 5 tables: PRODUCTS, CATEGORIES, URLS, URLPRODUCTS and URLCATEGORIES.
Table PRODUCTS has all the information of the product and an autoincrement primary key pid.
Same for CATEGORIES (cid).
URLS has got 2 columns: autoincrement primary key uid and unique key url.
The other two columns are the combination of PRODUCTS and URLS or CATEGORIES and URLS.
What structure should they have, to avoid one product to have the same url than another one or a category and to have only one url per product or category?
Your requirement seems to you have separate URL for each product and category.
Will like to add one point that every 'product' belongs to atleast one category, so there should be a column in product for categoryId as foreign key from 'Category' tbl.
Coming to you use case:
I think there should be one more column in product & category table named 'uid' which will be foreign key from URL table, this will ensure each product/category has only one url.
Thus no need to create tbls URLPRODUCTS and URLCATEGORIES (many to many relationship case) as your req is for one to one.

MS Access Creating a New Order And Orderline

I have a Customer table, an Order table, an Orderline table and a Product table. All of them have an Autonumber field as their primary key, and Orderline has a foreign key reference to Order ID on Order table:
ORDER
-----
Order ID - Autonumber
Customer ID - Number
...
ORDERLINE
---------
OrderLine ID - Autonumber
Order ID - FK to Order
Product ID - FK to Product
Quantity
PRODUCT
-------
Product ID - Autonumber
Product details...
I have a form where I can choose a customer, and then a list of records from the Orderline table, and a query which I reference from this sub-form which lists the Order ID, Orderline ID, Product ID, Product details...
I have 2 problems.
All the orders appear, and I only want the ones associated with this order, (which should be none when the form first loads).
When I enter a Product ID that I want to add to a new order, I am expecting a new Order ID to appear, (Autoincremented) AND a new Orderline ID, (Autoincremented) and the details of the product that I have selected, corresponding to theProduct ID` I have entered, but instead I get this error message:
The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again
The thing is, the tables should create me unique keys when I try to create the new record, and when I go into each table directly and enter a new record, the autonumber does work and does create a unique key - it is just when it is trying to create both the Order ID and the Orderline ID at the same time that it seems to be failing.
I should say, I have spent days on this, searched countless search engines, watched whole series of YouTube videos on creating Order forms but to no avail. Anyone who understands Access I am sure would be able to help me, as I would be able to help anyone in a similar circumstance in a matter of minutes if this was a problem in SQL.
When you create a sub-form you have to specify the relationship between the parent and sub-form. the same relationship you have created for your tables. Then only Access will filter the records for you.
Regarding your question. You should create a new [order] record in [order] table where you will be entering/selecting [customer_id, staff_id, order details ect]
one order can have more than one items so your [order_items] table (i assume orderline is the term you use for this table) exists of
order_id
product_id (order_id, product_id composite key)
quantity
price
etc..
Now when you want to start taking order you need to create a new form that is bound to tbl_order. In the frm_order you will have a sub-from which is bound to tbl_oder_items (in your case orderline)
The frm_order and frm_oder_items should be have a relationship. usually when you drag the table to create the subform ACCESS will ask to set the relationship. if you create the subform manually:
Select the sub-form
go to property sheet
select the link master field : order_id
select the link child field : order_id
Now when you open the frm_order it will show all the records (in other words all the products the order has in its list) from the tbl_order_items table.
Your tbl_order_item /orderline table also referencing to the product table via the product_id field.
Insert a combobox in the frm_order_items and bound it to the product_id. The combobox's rowsource would be
select product_id, product_name from tbl_product
This error message will occur:
'The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again'
when you try to add a product twice for the same order. instead you should increase the quantity for the product.
Try this and let us know how it went.

creating table in database bookshelf where one book can have multiple category

I'm creating a database of bookshelf.
I have a table named BookInfo which contains information regarding book title , category and many other properties related to it.
I have different table named category which have categoryID and categoryName with it.
Problem : I want to insert multiple category for single book information.waht would be the feasible solution.
The solution is normalize your DB.
Is not correct if you have more Category tables. You must use one Category table, then to link it to your BookInfo table you must create a middle table, for example, named, CategoryBook, where your middle table must be these fields:
ID (your PK table)
field PK BookInfo (as FK)
field PK Category (as FK)
Alternatively, your middle table can be built as follow:
PK BookInfo (as FK)
PK Category (as FK)
where two upper field are the PK of your table
You can create a mapping table as "Book_Category" which will have
BookID, CategoryID and if you want create a composite primary key for "Book_Category" table by combining both the columns.
You must have one more table to handle it.
OR
You have to add into BookInfo table only.
OR
Category column should hold different categoryID's

multiple column values in mysql

I need to make a table 'Movies' which will have columns:
ID Title Description Category etc
And another one called 'Movie_Categories' containing, for example
ID Category
1 Action
2 Adventure
3 Triller
but since category in table Movies will have multiple choices what is the correct way to do this?
should i use comma-separated values like someone said in this post Multiple values in column in MySQL or is there a better way?
This is a many-to-many relationship.
You need a join table to make it right, such as :
CREATE TABLE film_category (
category_id int,
film_id int,
PRIMARY KEY (category_id, film_id)
);
DO NOT GO FOR COMMA-SEPARATED VALUES. NEVER.
Having said that. Bear in mind that when you have a so called many-to-many relationship, that is, a relationship where you can have one category with many movies and one movie with many categories, you will always need to generate an additional table.
This table will only need the Primary Keys of each of the other 2 tables and will have a compound key.
So the schema will end up being:
Movies(ID, Title, Description, Category)
Categories(ID, Category)
Movies_Categories(ID_Movie, ID_Category)
In bold are the primary keys.
In order to get all the categories for a movie you will just have to join each of the three tables.
A final comment about having multi-valued fields is that your table will not be in First Normal Form which will, sooner or later, give you lots of headaches.
The last thing to do is have a non normalized table by storing comma separated values.
*You should have a table movies and a table for categories.
You should create a mapping table which will map the movieId to the categoryId*

MySql "Many to One" table design

I am new to DB design and I am having some trouble finding info on how to define a "Many to One" relationship. I can find all sorts of info on "One to Many" and "Many to Many" but nothing on "Many to One". My hangup is how to store the data. What I have is one table called "Categories" then I have another table called "Inventory", each "Inventory" item can belong to multiple "Categories".
How do I store multiple "Categories" in a single "Inventory" row? Should I have a intermediate table that stores the "Categories" ID with the corresponding "Inventory" ID? Or would adding something like a JSON string that has the "Categories" ID's in the "Inventory" row be the right way to do this? Or is there a way to store an Array of "Categories" ID's in the "Inventory" row?
Thanks allot for the help!
the correct term of Many to One is One to Many. simply create a table like this,
CREATE TABLE Categories
(
CategoryID INT Primary KEY,
CategoryName
);
CREATE TABLE InventoryList
(
ProductID INT Primary KEY,
CategoryID INT,
ProductName VARCHAR(50),
CONSTRAINT tb_fk FOREIGN KEY (CategoryID) REFERENCES Categories(CategoryID)
);
First I would suggest that you download mysql workbench - it gives you a nice visual db design mode so you can see how things hang together (creates foreign key relationships etc etc for you).
In this instance this is actually a many-to-many relationship. as such you will need a category table, an inventory table and a category_has_inventory table (or inventory_has_category depending on semantics) where you store the id of the inventory and category in each tuple - workbench even creates this table for you when using the many-to-many relationship tool.
Pop back on here if you need further help.
IF a category can only contain one inventory item then you could create a one-to many relationship by adding inventory_id to the category table but that sounds wrong to me.
"Many to one" is just "One to many" looked at from the other end.
Just add a column inventory_id to the Categories table.
If not only each "Inventory" item can belong to multiple "Categories" but also each "Categories" item can belong to multiple "Inventory" items, than you have a many-to-many relation for which you need a intermediate table with category_id and inventory_id.