Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何为多个表中的值添加SQL约束_Mysql_Sql_Spring_Hibernate_Spring Data - Fatal编程技术网

Mysql 如何为多个表中的值添加SQL约束

Mysql 如何为多个表中的值添加SQL约束,mysql,sql,spring,hibernate,spring-data,Mysql,Sql,Spring,Hibernate,Spring Data,我正在使用MySQL 我有以下几张表 User(UserID, UserTypeID, AccountID) Account(AccountID, AccountTypeID) Permission(PermissionID) UserType(UserTypeID) AccountType(AccountTypeID) UserPermission(UserID, PermissionID) PermissionRule(UserTypeID, AccountTypeID, Permissio

我正在使用MySQL

我有以下几张表

User(UserID, UserTypeID, AccountID)
Account(AccountID, AccountTypeID)
Permission(PermissionID)
UserType(UserTypeID)
AccountType(AccountTypeID)
UserPermission(UserID, PermissionID)
PermissionRule(UserTypeID, AccountTypeID, PermissionID)
是否可以使用SQL约束限制以下内容? 当权限插入到
UserPermission
表中时,该用户的
UserTypeID
、该用户帐户中的
AccountTypeID
以及插入的
PermissionID
应出现在
PermissionRule
表中

感觉这可能更适合于业务规则或过程/触发器,但想知道是否有任何方法可以限制使用我不知道的SQL约束


我将Spring数据与Hibernate一起使用。因此,任何基于spring或hibernate注释的限制也很有用。

如果是Oracle,答案是使用“”

MySQL检查约束

CHECK子句已解析,但被所有存储引擎忽略。参见第1.8.2.3节“外键差异”


根据您希望约束的行为方式,您可能可以使用外键约束,并借助物化视图

我现在假设,您想要的是:(
UserTypeID,AccountTypeID,PermissionID)
的三元组将出现在
PermissionRule
表中。所有字段都存在于
UserPermission

如果3元组在
PermissionRule
中是唯一的,则只需创建一个外键约束即可。如果没有,您可以基于
从PermissionRule
中选择DISTINCT UserTypeID、AccountTypeID、PermissionID并从unique约束中引用该表来创建物化视图

如果要约束的3个字段在
UserPermission
中不存在,但必须从其他表中查找,则可以创建一个物化视图来执行必要的联接,并将外键放在该表上

MySQL并不真正支持物化视图,但您可以使用触发器和普通表手动创建它们


如本文所述:

主键/外键约束将部分满足您的行为要求。你能从应用层处理这个逻辑吗?我肯定能在应用层处理这个逻辑。但是想知道我们是否可以从SQL中做任何事情。特别是,在某些情况下,当我删除PermissionRule中的一行时,我希望从UserPermission中删除适用的条目。我想我可能不得不为这种情况编写程序或触发器。。。