mysql查询、增加、删除外键约束

本文适用场景:导入数据时,由于有外键关联关系,导入不成功,采取先查询关联关系,将删除、增加的查询脚本分别运行 之后保存下来查询结果分别是删除脚本和添加脚本,然后运行保存下来的删除外键约束关系脚本,导入数据,导入成功后,再执行保存下来的添加外键关联关系脚本。

 

增加:

SELECT DISTINCT
	'alter table ' 操作,
	C.TABLE_NAME 子表名称,
	' ADD CONSTRAINT ' 增加外键约束,
	C.CONSTRAINT_NAME 约束名,
	' FOREIGN KEY(' 外键字段,
	C.COLUMN_NAME 子表字段,
	') ' 反括号,
	' REFERENCES ' 关联,
	C.REFERENCED_TABLE_NAME 父表名称,
	'(' 括号,
	C.REFERENCED_COLUMN_NAME 父表字段,
	') ' 反括号 ,
  #T.TABLE_COMMENT          表注释,
	' ON UPDATE ' 更新,
	 R.UPDATE_RULE            约束更新规则,
	' ON DELETE ' 删除,
	 R.DELETE_RULE            约束删除规则,
	';'
FROM
	INFORMATION_SCHEMA.KEY_COLUMN_USAGE C
JOIN INFORMATION_SCHEMA. TABLES T ON T.TABLE_NAME = C.TABLE_NAME
JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS R ON R.TABLE_NAME = C.TABLE_NAME
AND R.CONSTRAINT_NAME = C.CONSTRAINT_NAME
AND R.REFERENCED_TABLE_NAME = C.REFERENCED_TABLE_NAME
WHERE
	C.REFERENCED_TABLE_NAME IS NOT NULL
AND T.TABLE_NAME LIKE 'jc_%'
AND C.TABLE_SCHEMA = 'jfjyypt';

增加的结果:

mysql查询、增加、删除外键约束

复制之后执行就行.

查询:


SELECT DISTINCT C.TABLE_SCHEMA            拥有者,
					 C.TABLE_NAME             子表名称,
           C.COLUMN_NAME            子表字段,
           C.REFERENCED_TABLE_NAME  父表名称 ,
           C.REFERENCED_COLUMN_NAME 父表字段 ,
         
           C.CONSTRAINT_NAME        约束名,
           T.TABLE_COMMENT          表注释,
           R.UPDATE_RULE            约束更新规则,
           R.DELETE_RULE            约束删除规则
      FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE C
      JOIN INFORMATION_SCHEMA. TABLES T
        ON T.TABLE_NAME = C.TABLE_NAME
      JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS R
        ON R.TABLE_NAME = C.TABLE_NAME
       AND R.CONSTRAINT_NAME = C.CONSTRAINT_NAME
       AND R.REFERENCED_TABLE_NAME = C.REFERENCED_TABLE_NAME
      WHERE C.REFERENCED_TABLE_NAME IS NOT NULL
						AND T.TABLE_NAME like 'jc_%' AND C.TABLE_SCHEMA = 'jfjyypt'

 ; 

#ALTER TABLE jc_acquisition DROP FOREIGN KEY 

查询结果如下:

mysql查询、增加、删除外键约束

删除:

SELECT DISTINCT
	'alter table ' 操作,
	C.TABLE_NAME 子表名称,
	# C.REFERENCED_TABLE_NAME  父表名称 ,
	# C.REFERENCED_COLUMN_NAME 父表字段 ,
	' drop  foreign key ' 删除外键约束,
	C.CONSTRAINT_NAME 约束名 ,
  ';' 分号
  #T.TABLE_COMMENT          表注释
	#R.UPDATE_RULE            约束更新规则,
	#R.DELETE_RULE            约束删除规则
FROM
	INFORMATION_SCHEMA.KEY_COLUMN_USAGE C
JOIN INFORMATION_SCHEMA. TABLES T ON T.TABLE_NAME = C.TABLE_NAME
JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS R ON R.TABLE_NAME = C.TABLE_NAME
AND R.CONSTRAINT_NAME = C.CONSTRAINT_NAME
AND R.REFERENCED_TABLE_NAME = C.REFERENCED_TABLE_NAME
WHERE
	C.REFERENCED_TABLE_NAME IS NOT NULL
AND T.TABLE_NAME LIKE 'jc_%'
AND C.TABLE_SCHEMA = 'jfjyypt';

删除结果:

mysql查询、增加、删除外键约束

复制之后保存下来,在需要执行的时候才去执行即可。删除时 ,务必先复制好已经添加的外键。

上一篇:[ERR] 1217 - Cannot delete or update a parent row: a foreign key constraint


下一篇:添加外键约束