gpt4 book ai didi

mysql - 如何创建一个规则以在 bool 列中的许多假之间只接受一个真?

转载 作者:行者123 更新时间:2023-11-28 23:37:15 24 4
gpt4 key购买 nike

在一个问题(另一个表)的一组备选方案(一个表)中,如果用户没有选择,其中一个备选方案可以是默认的.

因此,如果我有一个 bool 列来设置默认选择的一组备选方案中的默认备选方案,我如何告诉数据库(我正在使用 MariaDB)只允许一个在一组指向 questions 表中的特定问题的备选方案中,alternative 设置为 true?

示例:

create table `alternatives` (
`id` serial,
`question_id` bigint unsigned not null,
`title` serial,
`default_choice` boolean
);

insert into `alternatives` values (1, 1, "option a", false); <- ok
insert into `alternatives` values (2, 1, "option b", false); <- ok
insert into `alternatives` values (3, 1, "option c", false); <- ok
insert into `alternatives` values (4, 1, "option d", false); <- ok
insert into `alternatives` values (5, 1, "user didn't choose", TRUE); <- ok
insert into `alternatives` values (6, 1, "none of the above", true); <-- SHOULD RAISE ERROR

最佳答案

像这样的东西应该可以工作(如果找到任何具有真实值的记录,它会引发异常):

delimiter //
CREATE TRIGGER check_true BEFORE INSERT ON alternatives
FOR EACH ROW
BEGIN
IF EXISTS (SELECT * FROM alternatives
WHERE
(question_id=NEW.question_id)
AND (default_choice = true)
AND (NEW.default_choice = true) THEN
SIGNAL SQLSTATE '45000'; -- code for unhandled user-defined exception
END IF;
END;//

关于mysql - 如何创建一个规则以在 bool 列中的许多假之间只接受一个真?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35435277/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com