检查SQL约束值

时间:2013-12-10 09:03:41

标签: php mysql sql postgresql

是否可以检查现有约束的特定值?

例如,我想检查FOREIGN KEY约束是ON DELETE SET NULL还是ON DELETE NO ACTION

如果存在约束,我只找到解决方案,但不存在特定值。

2 个答案:

答案 0 :(得分:1)

正如dev-null-dweller在their answer中建议的那样:

  

获取给定表的外键的简单方法:

SELECT
    `column_name`, 
    `referenced_table_schema` AS foreign_db, 
    `referenced_table_name` AS foreign_table, 
    `referenced_column_name`  AS foreign_column 
FROM
    `information_schema`.`KEY_COLUMN_USAGE`
WHERE
    `constraint_schema` = SCHEMA()
AND
    `table_name` = 'your-table-name-here'
AND
    `referenced_column_name` IS NOT NULL
ORDER BY
    `column_name`;

或者另一种方式,suggested by Lo Sauer,是:

SELECT * FROM information_schema.table_constraints 
         WHERE table_schema = 'dbname' AND table_name='mytable';

答案 1 :(得分:1)

对于Postgres,这将是:

select tc.table_schema||'.'||tc.table_name as referencing_table, 
       ctu.table_schema||'.'||ctu.table_name as referenced_table_name,
       rc.update_rule, 
       rc.delete_rule
from information_schema.table_constraints tc
  join information_schema.referential_constraints rc 
    on tc.constraint_catalog = rc.constraint_catalog 
   and tc.constraint_schema = rc.constraint_schema 
   and tc.constraint_name = rc.constraint_name
  join information_schema.constraint_table_usage ctu 
    on ctu.constraint_catalog = rc.unique_constraint_catalog
   and ctu.constraint_schema = rc.unique_constraint_schema
   and ctu.constraint_name = rc.unique_constraint_name
where tc.table_name = 'foobar'
  and tc.table_schema = 'public'
  and tc.constraint_type = 'FOREIGN KEY'

但这不适用于MySQL