gpt4 book ai didi

MySQL 约束 - 一组中的一列必须是非空的?

转载 作者:行者123 更新时间:2023-11-30 23:25:48 27 4
gpt4 key购买 nike

我有一个 MySql (InnoDb) 表,表示对许多类型的对象之一所做的评论。因为我正在使用 Concrete Table Inheritance ,对于下面显示的每种类型的对象(商店、类别、项目),我都有一个不同的外键。对于每条记录,必须恰好设置一个外键,另外两个必须为空。我如何在 MySql 中指定此约束?

CREATE TABLE `tbl_comment` (
`comment_id` bigint(20) NOT NULL AUTO_INCREMENT, /* primary key */
`_user_id` bigint(20) NOT NULL, /* foreign key to user table - always set (NOT NULL) */

`store_id` int(11) DEFAULT NULL, /* foreign key to store table */
`category_id` bigint(20) DEFAULT NULL, /* foreign key to category table */
`item_id` bigint(20) DEFAULT NULL, /* foreign key to item table */
...

最佳答案

尝试添加以下触发器

CREATE TRIGGER on_insert AFTER INSERT ON `tbl_comment`
FOR EACH ROW
BEGIN
SET NEW.category = NULL, NEW.item = NULL;
END;

关于MySQL 约束 - 一组中的一列必须是非空的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13427720/

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