默认约束是实际约束吗?

发布于 2025-02-07 18:18:29 字数 141 浏览 1 评论 0原文

在SQL中,我看到了几种类型的约束,例如主键。不是零,外键等。但是我现在偶然发现了默认约束,我感到困惑。

它阻止发生什么?任何查询都不会遵守吗?

如果没有查询由于默认约束而失败,那真的是一个约束吗?

谢谢。 一个困惑的开发人员

In SQL I see several types of constraints, like PRIMARY KEY. NOT NULL, FOREIGN KEY, etc. But I stumbled on DEFAULT constraints now and I'm confused.

What does it prevent to happen? Will any query fail to adhere by it?

If no query will ever fail because of a DEFAULT constraint, is it really a constraint?

Thank you.
A confused developer

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

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

发布评论

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

评论(3

绾颜 2025-02-14 18:18:29

如果列是而不是null

喜欢

CREATE TABLE mytable (val int NOT NULL)

,并且您尝试的

 INSERT NTO mytable VALUES (NULL)

您会遇到错误,因为TE数据库无法用default value替换null,因为它不存在。

因此,它将插入到中。

if a column is Not NULL

Like

CREATE TABLE mytable (val int NOT NULL)

and you try

 INSERT NTO mytable VALUES (NULL)

You will get an error, as te database can't replace the NULL with a DEFAULT value, because it doesn't exist.

so it constraints the INSERT INTO

请止步禁区 2025-02-14 18:18:29

检查以下答案是否有助于您了解默认约束。
https://stackoverflow.com/a/1213316/7056491

Check if the following answer helps you understanding about DEFAULT constraint.
https://stackoverflow.com/a/1213316/7056491

香草可樂 2025-02-14 18:18:29

如果列有默认约束,并且insertupdate语句不提供该列的值,则MySQL将使用默认值中指定的默认值约束。

因此,表:

CREATE TABLE Defaults (
    Age int,
    Gender varchar(255) DEFAULT 'Female'
);

您可以插入:

INSERT INTO Defaults (`Age`) VALUES ('4');

年龄将为4岁,性别将是“女性”。

默认约束不限制任何值的添加,也不像其他约束一样强制执行规则,但是它确实提供了适当的预定义值以保持域的完整性完整。

If a column has a DEFAULT constraint and the INSERT or UPDATE statement doesn’t provide the value for that column, MySQL will use the default value specified in the DEFAULT constraint.

So for table:

CREATE TABLE Defaults (
    Age int,
    Gender varchar(255) DEFAULT 'Female'
);

You can Insert:

INSERT INTO Defaults (`Age`) VALUES ('4');

Age will be 4, and Gender will be 'Female'.

The DEFAULT constraint does not RESTRICT the addition of any value nor does it enforce a rule like the other constraints, but it does provide proper predefined values to keep domain integrity intact.

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