MYSQL 约束 - 多重检查

发布于 2024-08-23 16:37:23 字数 315 浏览 3 评论 0原文

好吧,我在这里为我正在处理的数据库编写一些约束,我想知道我是否可以执行以下操作:

ALTER TABLE Course
ADD CONSTRAINT cs_level
CHECK (clevel in ('P','I','II','III'))

...而不是这样:

ALTER TABLE Course
ADD CONSTRAINT cs_level
CHECK (clevel = 'P' OR clevel = 'I' OR clevel = 'II' OR clevel = 'III')

Well i am here writing some constraints for a db I am working on and i was wondering if I could do the following:

ALTER TABLE Course
ADD CONSTRAINT cs_level
CHECK (clevel in ('P','I','II','III'))

...instead of this:

ALTER TABLE Course
ADD CONSTRAINT cs_level
CHECK (clevel = 'P' OR clevel = 'I' OR clevel = 'II' OR clevel = 'III')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

半衾梦 2024-08-30 16:37:23

即使 MySQL 强制执行 CHECK 约束,我仍然会创建一个 COURSE_LEVEL 表:

  • COURSE_LEVEL_CODE、VARCHAR(3)、主键
  • COURSE_LEVEL_DESCRIPTION、VARCHAR(120)

...并在 COURSE 表的 clevel 列上创建 FOREIGN KEY 约束:

ALTER TABLE COURSE
ADD FOREIGN KEY (clevel) REFERENCES COURSE_LEVEL(COURSE_LEVEL_CODE)

Even if MySQL enforced CHECK constraints, I'd still be creating a COURSE_LEVEL table:

  • COURSE_LEVEL_CODE, VARCHAR(3), primary key
  • COURSE_LEVEL_DESCRIPTION, VARCHAR(120)

...and create a FOREIGN KEY constraint on the COURSE table, clevel column:

ALTER TABLE COURSE
ADD FOREIGN KEY (clevel) REFERENCES COURSE_LEVEL(COURSE_LEVEL_CODE)
锦上情书 2024-08-30 16:37:23

不幸的是,MySQL 不支持 CHECK 约束。它们被解析但被忽略。

来自参考手册

CHECK 子句被解析,但被所有存储引擎忽略。

您可以尝试在插入行之前将此检查约束放入业务逻辑中。

正如Joe Celko在他的书中Joe Celko 的 Smarties SQL :

开源领域已经出现了小型“伪SQL”产品。 MySQL 等语言在语法和语义上与标准 SQL 有很大不同,通常只不过是借用保留字的文件系统接口

确实有点苛刻,但在某种程度上他是正确的,因为 MySQL 不支持一堆标准SQL 功能。

Unfortunately, MySQL does not support the CHECK-constraints. They are parsed but ignored.

From the reference manual:

The CHECK clause is parsed but ignored by all storage engines.

You can try to put this check constraint in your business logic before inserting the row.

As Joe Celko says in his book Joe Celko's SQL for Smarties:

Small "pseudo-SQL" products have appeared in the open source arena. Languages such as MySQL are very different in syntax and semantics from Standard SQL, often being little more than a file system interface with borrowed reserved words

A little harsh indeed, but in a way he's correct, since MySQL doesn't support a bunch of Standard SQL features.

林空鹿饮溪 2024-08-30 16:37:23

MySQL只支持外键约束,不支持检查约束。无论您从哪里获得该语法,都不是 MySQL 手册。

MySQL only supports foreign key constraints, not check constraints. Wherever you got that syntax from, it wasn't the MySQL manual.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文