How do I automatically detect and delete duplicate Foreign-key constraints in Postgresql
My Postgresql database has a large number of duplicate foreign key constraints on tables for example
"fkb43bb0b712b68565" FOREIGN KEY (owner_id)开发者_StackOverflow社区 REFERENCES usr(id)
"fkb43bb0b71b63ed43" FOREIGN KEY (owner_id) REFERENCES usr(id)
They're doing the same thing but have unique names.
How can I automatically detect and delete such duplicates?
Thanks
J
SELECT
pc.conname as constraint_name,
--conrelid as child_table_id,
pclsc.relname as child_table,
--pc.conkey as child_column_id,
pac.attname as child_column,
--confrelid as parent_table_id,
pclsp.relname as parent_table,
--pc.confkey as parent_column_id,
pap.attname as parent_column,
nspname as schema_name
FROM
(
SELECT
connamespace,conname, unnest(conkey) as "conkey", unnest(confkey)
as "confkey" , conrelid, confrelid, contype
FROM
pg_constraint
) pc
JOIN pg_namespace pn ON pc.connamespace = pn.oid
-- and pn.nspname = 'panmydesk4400'
JOIN pg_class pclsc ON pc.conrelid = pclsc.oid
JOIN pg_class pclsp ON pc.confrelid = pclsp.oid
JOIN pg_attribute pac ON pc.conkey = pac.attnum and pac.attrelid = pclsc.oid
JOIN pg_attribute pap ON pc.confkey = pap.attnum and pap.attrelid = pclsp.oid
ORDER BY pclsc.relname
above query will return all the foreign key constraint from that u simply delete the duplicate entries.
Note : if you remove the comments from above query you can view the relID and ColID and the query should work for all the schema in the database
SELECT
array_agg(pc.conname) as duplicated_constraints,
pclsc.relname as child_table,
pac.attname as child_column,
pclsp.relname as parent_table,
pap.attname as parent_column,
nspname as schema_name
FROM
(
SELECT
connamespace,conname, unnest(conkey) as "conkey", unnest(confkey)
as "confkey" , conrelid, confrelid, contype
FROM
pg_constraint
) pc
JOIN pg_namespace pn ON pc.connamespace = pn.oid
JOIN pg_class pclsc ON pc.conrelid = pclsc.oid
JOIN pg_class pclsp ON pc.confrelid = pclsp.oid
JOIN pg_attribute pac ON pc.conkey = pac.attnum and pac.attrelid = pclsc.oid
JOIN pg_attribute pap ON pc.confkey = pap.attnum and pap.attrelid = pclsp.oid
GROUP BY child_table, child_column, parent_table, parent_column, schema_name HAVING COUNT(*)>1
ORDER BY child_table, child_column
will list only duplicated foreign key constraints in Postgresql
Constraints are stored in pg_constraint, just query this view to find double constraints.
精彩评论