简体   繁体   English

如何设置MySQL约束以禁止单行的某些列值?

[英]How do I make a MySQL constraint to disallow certain column values for a single row?

I have a Table. 我有一张桌子。

word      singular_only      plural_only
homework       1                  0       #homework has no plural
dog            0                  0       #dog and dogs are both real words
scissors       0                  1       #scissor is not a valid singular noun 
 x             1                  1       #should not be insertable

I want to allow the first three rows but not the fourth. 我想允许前三行,但不允许第四行。 How do I add a constraint for this. 如何为此添加约束。 The values in singular_only and plural_only are boolean. 单数和复数中的值是布尔值。 The columns mean whether a word only has a plural form or singular form or both (if both booleans are false). 列表示一个单词是仅具有复数形式还是单数形式,或者两者都具有(如果两个布尔值均为假)。 Obviously if something can only be singular it cannot also be plural. 显然,如果某事物只能是单数,那么它也不能是复数。 What is the best way to model this in MySQL. 在MySQL中对此建模的最佳方法是什么。

Is it better to add this constraint in MySQL or to ensure that the overlying code never tries to insert these values. 最好在MySQL中添加此约束,或者确保上层代码从不尝试插入这些值。

In other words 换一种说法

singular_only NAND plural_only should also be true

You can't add a constraint on one column based on another column except to constrain matching values, which you do not want to do. 除了约束匹配值(您不想这样做)之外,您不能在基于另一列的一列上添加约束。 You should be using a single column to set "singular/plural" status. 您应该使用单个列来设置“单/复”状态。 There are several solutions including using an integer (0,1,2 for the three possible states), an enum, and even another table. 有几种解决方案,包括使用整数(三个可能的状态分别为0,1,2),枚举甚至另一个表。 I'll leave the choice up to you, but I would favor the flexibility and clarity of another table. 我将选择权留给您,但我希望另一张桌子具有灵活性和清晰度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM