MySQL:获取约束名称并将其放在一个语句中

时间:2015-08-04 20:34:30

标签: mysql sql dynamic ddl bulk

我从以下地址获得约束名称:

SELECT
  constraint_name
FROM
  information_schema.REFERENTIAL_CONSTRAINTS
WHERE
  constraint_schema = 'db' AND table_name = 'table';

然后从表中删除它。它在本地计算机上手动完成时有效。现在它正在弄乱我的Jenkins build的db迁移脚本。
有没有办法在一个声明中这样做?

  
    

更新     
    以下查询给了我用户root @ localhost

的拒绝访问权限   
DELETE
FROM
  information_schema.REFERENTIAL_CONSTRAINTS
WHERE
  constraint_schema = 'db' AND table_name = 'table';

1 个答案:

答案 0 :(得分:2)

要自动生成要运行的丢弃约束:

SELECT concat('ALTER TABLE ', TABLE_NAME, ' DROP FOREIGN KEY ', CONSTRAINT_NAME, ';') as theString
FROM information_schema.key_column_usage 
WHERE CONSTRAINT_SCHEMA = 'so_gibberish' 
AND referenced_table_name IS NOT NULL;

+---------------------------------------------------+
| theString                                         |
+---------------------------------------------------+
| ALTER TABLE fc_junction DROP FOREIGN KEY fc_cat;  |
| ALTER TABLE fc_junction DROP FOREIGN KEY fc_food; |
+---------------------------------------------------+

自动生成要运行的字符串。如有必要,按摩订购。你离开了。请注意,在Workbench / sqlyog中,您当然不会有表栏输出。