我想删除与表关联的所有外键.
我首先使用下面的方法识别与之关联的外键
SELECT DISTINCT constraint_name
FROM information_schema.key_column_usage
WHERE table_name = 'crm_campaign_offer_customer_groups'
AND table_schema = 'schema001'
AND constraint_name LIKE '%fkey%'
Run Code Online (Sandbox Code Playgroud)
然后使用类似的语句循环遍历每个删除外键
ALTER TABLE crm_campaign_offer_customer_groups DROP CONSTRAINT crm_campaign_offer_customer_groups_variable_1_fkey1;
Run Code Online (Sandbox Code Playgroud)
发生的问题是它首先截断外键表达式然后尝试删除截断的表达式
NOTICE: identifier "..." will be truncated to "..."
ERROR: constraint "..." of relation "..." does not exist
Run Code Online (Sandbox Code Playgroud)
它似乎是截断标识符> 63个字符,但我希望有一个替代,因为表和变量命名约定已经设置
对于那些最终到达这里的人,请仔细检查您的密钥名称。Postgres 还会在创建时预先截断生成的名称,因此您需要在 DROP 上匹配此截断才能正确引用它。
ALTER TABLE really_long_table_more_than_63_chars ADD PRIMARY KEY (fields);
Run Code Online (Sandbox Code Playgroud)
->
ALTER TABLE really_long_table_more_than_63_chars DROP CONSTRAINT
really_long_table_more_than_63_c_pkey;
Run Code Online (Sandbox Code Playgroud)
在创建约束或索引而不指定名称时,Postgres 的行为似乎是:
生成名称为{table_name}+_pkey或{table_name}+_check
如果上面的 name.length > 63 个字符,则截断得{table_name}足够短,使得组合字符串为 63。即{table_name}[:58]+_pkey或{table_name}[:57]+_check