[英]How to create a Constraint for 2 columns mysql
I have have created a database with 3 tables: 我已经创建了一个包含3个表的数据库:
Products 产品展示
Categories 分类目录
Subcategories 子类别
In my products table I have a category and a subcategory column: 在我的产品表中,我有一个类别和一个子类别列:
| product_name | category | subcategory|
----------------------------------------
| varchar | int | int |
As of right now the category column references the categories table id and the subcategory column references the subcategories id. 到目前为止,类别列引用了类别表ID,子类别列引用了子类别ID。
The categories column has an id and a category name column: 类别列具有一个ID和一个类别名称列:
| id | category_name |
----------------------
|int | varchar |
The subcategories column has an id, sub category and a parent column which is a foreign key that references the categories(id) column. 子类别列具有一个id,子类别和一个父列,该父列是引用category(id)列的外键。
| id | subcategory_name | parent |
---------------------------------
|int | varchar | int |
I wanted to know if there is a way to add a constraint to the products's 'subcategories' column so that one would only be able to add a value if it was a legitimate child of the parent category. 我想知道是否有一种方法可以在产品的“子类别”列中添加约束,以便只有在其是父类别的合法子项时才能添加值。
Forgive me if this question has been answered already. 如果这个问题已经回答,请原谅我。 I do not know the proper name for what I am trying to do. 我不知道我要做什么的专有名称。
1 - you can use program to verify before insert / update the sub-cat id 1-您可以使用程序在插入/更新子猫ID之前进行验证
2 - or you can use a trigger to run after each transaction 2-或者您可以使用触发器在每次交易后运行
3 - or you can redesign your category and sub-category table, it depends on how your category data look. 3-或者您可以重新设计类别和子类别表,这取决于类别数据的外观。
eg: 例如:
id category_name
---- -------------
10 cat 10
1011 kid of cat 10
20 cat 20
2020 kid of cat 20
4 - If you do not like above design, you can also design this way: 4-如果您不喜欢上面的设计,也可以这样设计:
id category parent_id
---- ------------- -----
10 cat 10 0
1010 kid of cat 10 10
20 cat 20 0
2020 kid of cat 20 20
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.