开发者

Need help setting up Foreign Key relationship in MySQL DB

开发者 https://www.devze.com 2023-01-26 19:13 出处:网络
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.

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 r开发者_如何学JAVAecord.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消