cod*_*one 0 mysql check-constraints
模式
\n create table course\n (course_id varchar(8), \n title varchar(50), \n dept_name varchar(20),\n credits numeric(2,0) check (credits > 0),\n primary key (course_id),\n foreign key (dept_name) references department (dept_name)\n on delete set null\n );\nRun Code Online (Sandbox Code Playgroud)\n我想将此数据添加到表中,但无法添加 0 学分。
\n\n\n\xe2\x80\x9cCS-001\xe2\x80\x9d,标题为\xe2\x80\x9c每周研讨会\xe2\x80\x9d,0学分
\n
插入查询
\nINSERT INTO `course`(`course_id`, `title`, `credits`) VALUES (\'CS-001\',\'Weekly Seminar\',\'0\');\nRun Code Online (Sandbox Code Playgroud)\n\n有没有其他方法可以在不改变表结构的情况下插入相同的数据?
\n该foreign_key_checks选项影响外键强制执行,而不影响检查约束强制执行。
mysql> set foreign_key_checks=0;
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO `course`(`course_id`, `title`, `credits`) VALUES ('CS-001','Weekly Seminar','0');
ERROR 3819 (HY000): Check constraint 'course_chk_1' is violated.
Run Code Online (Sandbox Code Playgroud)
您必须使用ALTER TABLE,但不必删除约束。
mysql> alter table course alter check course_chk_1 not enforced;
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> INSERT INTO `course`(`course_id`, `title`, `credits`) VALUES ('CS-001','Weekly Seminar','0');
Query OK, 1 row affected (0.00 sec)
Run Code Online (Sandbox Code Playgroud)
但是,一旦插入该行,就无法重新启用检查约束,因为启用约束时将重新检查行。
mysql> alter table course alter check course_chk_1 enforced;
ERROR 3819 (HY000): Check constraint 'course_chk_1' is violated.
Run Code Online (Sandbox Code Playgroud)
您可以随后删除或更新违反检查约束的行,然后重新启用约束。
如果您需要能够向credits列插入零值,那么这似乎check (credits > 0)不是该列的正确选择。也许需要如此check (credits >= 0)。
| 归档时间: |
|
| 查看次数: |
187 次 |
| 最近记录: |