简体   繁体   English

MySQL忽略检查约束

[英]mysql ignoring check constraint

I have this code and I want to implement it in MySQL but CHECK is not supported. 我有此代码,我想在MySQL中实现它,但不支持CHECK。 How would I do it? 我该怎么办?

CREATE TABLE Fare (
    type_of_passenger varchar(20),
    price FLOAT,
    PRIMARY KEY (type_of_passenger),
    CHECK (lower(type_of_passenger)='child' OR lower(type_of_passenger)='student' OR lower(type_of_passenger)='senior')
);

Are you sure you need that check? 确定要检查吗? As the primary key is type_of_passenger you will only ever be able to have three rows.. this seems like over-kill 因为主键是type_of_passenger您将只能拥有三行。

You could just INSERT those 3 rows and move on. 您只需INSERT这3行并继续。 If you reference this field in a foreign key, you'll be restricted to the values in the table anyway 如果您在外键中引用此字段,则无论如何您将只能使用表中的值

In fact as soon as you reference each value with a foreign key that uses ON UPDATE RESTRICT and ON DELETE RESTRICT you won't be able to change them anyway 实际上,只要您使用使用ON UPDATE RESTRICT和ON DELETE RESTRICT的外键引用每个值,便无论如何都无法更改它们

The only valid concern I can see here is that you want to allow a DB user to change the price but not the type_of_passenger 我在这里看到的唯一有效的担忧是您想允许数据库用户更改price而不是type_of_passenger

If you INSERT the correct (or stub) data to start with, you can then control table and column access via permissions 如果您INSERT正确的(或存根)数据作为开始,则可以通过权限控制表和列的访问

NB I would use a surrogate unsigned integer primary here and unique the string description, thus if I do need to change the string I can do it without worry, and without the performance hit of updating all the tables that reference it 注意:我将在这里使用替代的无符号整数主变量,并且对字符串描述进行唯一化,因此,如果我确实需要更改字符串,则可以不用担心,也不会影响更新所有引用它的表的性能

It looks like you're really trying to implement an ENUM : 看来您确实在尝试实现ENUM

type_of_passenger ENUM('child', 'student', 'senior')

By default MySQL doesn't validate ENUM values, so if you try to store something else it will store an empty string, but if strict SQL mode is enabled it will report an error. 默认情况下,MySQL不验证ENUM值,因此,如果您尝试存储其他内容,它将存储一个空字符串,但是如果启用了严格的SQL模式,它将报告错误。

Another alternative is to make this a foreign key to a table where you enter the valid values. 另一种选择是使它成为您在其中输入有效值的表的外键。

CREATE TABLE passenger_types (
    type VARCHAR(20) NOT NULL PRIMARY KEY
);
INSERT INTO passenger_types (type) VALUES
('child'), ('student'), ('senior');


CREATE TABLE Fare (
    type_of_passenger varchar(20),
    price FLOAT,
    PRIMARY KEY (type_of_passenger),
    CONSTRAINT FOREIGN KEY (type_of_passenger) REFERENCES passenger_types (type)
);

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

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