sql约束不允许两个标志为false

发布于 2025-01-28 00:27:55 字数 864 浏览 2 评论 0 原文

我有下表:

CREATE TABLE test(
   flag_1 boolean not null default true,
   flag_2 boolean not null default false
);

我想要一个不允许两个标志的约束。其中至少有一个需要是真实的。

示例:

INSERT INTO test VALUES(true, true);   // Should work
INSERT INTO test VALUES(true, false);  // Should work
INSERT INTO test VALUES(false, true);  // Should work
INSERT INTO test VALUES(false, false); // Should fail

我想到了以下内容:

ALTER TABLE test
ADD CONSTRAINT allow_only_one_false
CHECK 
(
    ( CASE WHEN flag_1 is false and flag_2 is false then 0 ELSE 1 END
    ) = 1
);

它确实有效,但不确定是否有一种更简单的方法来实现这一目标。

数据库小提琴:

谢谢

I have the following table:

CREATE TABLE test(
   flag_1 boolean not null default true,
   flag_2 boolean not null default false
);

I want a constraint that doesn't allow both flags to be false. At least one of them needs to be true.

Example:

INSERT INTO test VALUES(true, true);   // Should work
INSERT INTO test VALUES(true, false);  // Should work
INSERT INTO test VALUES(false, true);  // Should work
INSERT INTO test VALUES(false, false); // Should fail

I came up with the following:

ALTER TABLE test
ADD CONSTRAINT allow_only_one_false
CHECK 
(
    ( CASE WHEN flag_1 is false and flag_2 is false then 0 ELSE 1 END
    ) = 1
);

It does work but no sure if there is a simpler way of achieving the same.

Database Fiddle:

https://dbfiddle.uk/?rdbms=postgres_13&fiddle=78885662e4aee8bfee01c429f86f28c5

Thanks

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

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

发布评论

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

评论(2

计㈡愣 2025-02-04 00:27:55

你可以做

Check (flag_1 or flag_2)

You can do

Check (flag_1 or flag_2)
硪扪都還晓 2025-02-04 00:27:55

我认为您应该在更新后使用触发器来确保您的两个字段不正确。

[使用触发器] [1] https://www.educba.com/sql-after-update-trigger/

I think you should use the trigger after the update to make sure both of your fields are incorrect.

[Use Trigger][1]https://www.educba.com/sql-after-update-trigger/

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