约束在MYSQL表中? [英] Constraint in MYSQL table?

查看:54
本文介绍了约束在MYSQL表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Groups 的表,其中主键= Pkey .在群组中,有一个递归关联 Parent_group 引用 Pkey .我在关系 Groups 中将Parent_Group定义为外键.我正在使用MYSQL.

I have a table named Groups with primary key = Pkey. In Group there is a recursive association Parent_group references Pkey . I defined a Parent_Group as foreign key in relation Groups. I am using MYSQL.

餐桌人数:

+------+-----------+------------+----------+---------------+            
| PKey | GroupName | Region     |  Role    | Parent_Group  |
+------+-----------+------------+----------+---------------+            
| k1   | RootGroup | Jaipur     |  Admin   | NULL          | 
+------+-----------+------------+----------+---------------+            
| k2   | G2        | Alwar      |  Admin   | k1            |
+------+-----------+------------+----------+---------------+            
| k3   | G3        | Jaipur     |  Guest   | k3            | 
+------+-----------+------------+----------+---------------+            
| k4   | G4        | Alwar      |  Operator| k2            |
+------+-----------+------------+----------+---------------+            

查询创建表:

CREATE TABLE IF NOT EXISTS `groups` 
(
  `PKey` varchar(64) NOT NULL,
  `group_name` varchar(64) DEFAULT NULL,
  `Region` varchar(128) NOT NULL,
  `Role` varchar(128) NOT NULL,
  `parent_group` varchar(64) DEFAULT NULL, 
  PRIMARY KEY (`Pkey`),
  KEY `FK_ParentGroup_ChildGroup` (`parent_group`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Groups 表将随我的应用程序一起提供,其中只有一个 RootGroup 元组.

The Groups table will be shipped with my application with only one RootGroup tuple.

我要在表上施加两个约束吗?如下:

  1. 新插入的行的 Parent_group
  2. 不能为NULL值
  3. 添加约束,以防止删除 RootGroup 行.

我想知道,SQL是否有可能在SQL中运行(如果如何?),或者我必须在后端系统中处理?

I wants to know, Weather it is possible within SQL (if yes how?) or I have to handle in back-end systems?

可以使用触发器吗?

编辑:我想对表施加额外的约束,以使新的插入元组不能指向自身.例如

EDIT: I wants to impose an extra constraint on table So that a new inserting tuple can not point to itself. e.g.

mysql> INSERT INTO Employee VALUES ("8", "H", "BOSS",   "8");
Query OK, 1 row affected (0.04 sec)

应该失败吗?

推荐答案

关于您要施加的两个约束,有几件事:

There are a few things about the two constraints you wish to impose:

  1. 新插入的行的Parent_group列的值不能为NULL.

  1. New inserted row can not have NULL value for Parent_group column.

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆