在外键约束中获取ON DELETE ON UPDATE操作

时间:2013-04-29 14:47:46

标签: mysql

我试图在外键更改中执行操作(删除/更新时)。

我试图在INFORMATION_SCHEMA.key_column_usage中查看它:

SELECT * 
FROM `INFORMATION_SCHEMA`.`key_column_usage` 
WHERE `referenced_table_schema` = '{$this->dbName}'
AND `referenced_table_name` IS NOT NULL
AND `table_name` = '{$this->tableName}'

它显示如下:

0 => 
array (size=12)
  'CONSTRAINT_CATALOG' => string 'def' (length=3)
  'CONSTRAINT_SCHEMA' => string 'test' (length=4)
  'CONSTRAINT_NAME' => string 'profiles_ibfk_1' (length=15)
  'TABLE_CATALOG' => string 'def' (length=3)
  'TABLE_SCHEMA' => string 'test' (length=4)
  'TABLE_NAME' => string 'profiles' (length=8)
  'COLUMN_NAME' => string 'id' (length=2)
  'ORDINAL_POSITION' => string '1' (length=1)
  'POSITION_IN_UNIQUE_CONSTRAINT' => string '1' (length=1)
  'REFERENCED_TABLE_SCHEMA' => string 'test' (length=4)
  'REFERENCED_TABLE_NAME' => string 'users' (length=5)
  'REFERENCED_COLUMN_NAME' => string 'id' (length=2)

....

我也尝试了INFORMATION_SCHEMA.TABLE_CONSTRAITS而且我得到了:

0 => 
array (size=6)
  'CONSTRAINT_CATALOG' => string 'def' (length=3)
  'CONSTRAINT_SCHEMA' => string 'test' (length=4)
  'CONSTRAINT_NAME' => string 'PRIMARY' (length=7)
  'TABLE_SCHEMA' => string 'test' (length=4)
  'TABLE_NAME' => string 'profiles' (length=8)
  'CONSTRAINT_TYPE' => string 'PRIMARY KEY' (length=11)

....

在2个案例中没有关于删除/更新的操作。

我能得到它吗?怎么样?如果我当然可以。

2 个答案:

答案 0 :(得分:2)

REFERENTIAL_CONSTRAINTS信息架构中选择UPDATE_RULEDELETE_RULE

SELECT CONSTRAINT_NAME, UPDATE_RULE, DELETE_RULE
FROM   INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE  UNIQUE_CONSTRAINT_SCHEMA = '{$this->dbName}'
   AND REFERENCED_TABLE_NAME IS NOT NULL
   AND TABLE_NAME = '{$this->tableName}'

记录在案:

  

UPDATE_RULEDELETE_RULE的可能值为CASCADESET NULLSET DEFAULTRESTRICTNO ACTION。< / p>

答案 1 :(得分:0)

这取决于你想做什么。如果您只想在相关记录上更新外键,那么您正在使用CASCADE选项查找外键约束。请参阅this page并阅读有关级联的部分。如果您想要对记录的UPDATE / DELETE执行更复杂的操作,则需要触发器。有关创建触发器的语法,请参阅this page