Last active
May 27, 2022 18:49
-
-
Save lewiswalsh/f1d50108d9091648430b4f7d5ebfae34 to your computer and use it in GitHub Desktop.
Export all keys from a database #mysql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT CONCAT( | |
'ALTER TABLE ', fks.quotedSourceTableName, ' ', | |
'ADD CONSTRAINT ', fks.quotedConstraintName, ' ', | |
'FOREIGN KEY (', GROUP_CONCAT(fks.quotedSourceColumnName), ') ', | |
'REFERENCES ', fks.quotedTargetTableName, ' (', | |
GROUP_CONCAT(fks.quotedTargetColumnName), | |
') ', | |
'ON DELETE ', fks.deleteRule, ' ', | |
'ON UPDATE ', fks.updateRule, ';' | |
) | |
FROM ( | |
SELECT | |
CONCAT('`', kcu.CONSTRAINT_NAME, '`') AS quotedConstraintName, | |
CONCAT('`', kcu.TABLE_NAME, '`') AS quotedSourceTableName, | |
CONCAT('`', kcu.COLUMN_NAME, '`') AS quotedSourceColumnName, | |
CONCAT('`', kcu.REFERENCED_TABLE_NAME, '`') AS quotedTargetTableName, | |
CONCAT('`', kcu.REFERENCED_COLUMN_NAME, '`') AS quotedTargetColumnName, | |
rc.DELETE_RULE AS deleteRule, | |
rc.UPDATE_RULE AS updateRule | |
FROM information_schema.KEY_COLUMN_USAGE AS kcu | |
INNER JOIN information_schema.REFERENTIAL_CONSTRAINTS AS rc ON | |
kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME AND | |
kcu.TABLE_SCHEMA = rc.CONSTRAINT_SCHEMA | |
WHERE | |
kcu.TABLE_SCHEMA = '<database name>' AND | |
kcu.REFERENCED_COLUMN_NAME IS NOT NULL | |
ORDER BY | |
kcu.ORDINAL_POSITION DESC | |
) AS fks | |
GROUP BY | |
fks.quotedConstraintName, | |
fks.quotedSourceTableName, | |
fks.quotedTargetTableName, | |
fks.deleteRule, | |
fks.updateRule; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment