gpt4 book ai didi

postgresql - 获取将被级联截断的表列表

转载 作者:行者123 更新时间:2023-11-29 12:19:21 24 4
gpt4 key购买 nike

在 postgres 中,有没有一种方法可以获取也会被 TRUNCATE CASCADE 截断的表列表?

例如,假设我们有三个表:

a
b (depends on a)
c (depends on b)

TRUNCATE a CASCADE; 也会截断 bc。我们怎么能提前检查呢?

最佳答案

this的帮助下answer 你可以通过这个查询得到外部表名

SELECT tc.constraint_name
,tc.table_name
,kcu.column_name
,ccu.table_name AS foreign_table_name
,ccu.column_name AS foreign_column_name
FROM
information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
ON tc.constraint_name = kcu.constraint_name
JOIN information_schema.constraint_column_usage AS ccu
ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY' AND ccu.table_name = 'a'

使用另一个查询创建 View

CREATE VIEW vdepend_table
AS
SELECT s1.constraint_name
,s1.table_name
,s1.column_name
,s1.ordinal_position
,s2.table_name_ref
,s2.column_name_ref
,s2.ordinal_position_ref
FROM (
SELECT key_column_usage.constraint_name
,key_column_usage.table_name
,key_column_usage.column_name
,columns.ordinal_position
FROM information_schema.key_column_usage
JOIN information_schema.columns USING (
table_name
,column_name
)
) s1
JOIN (
SELECT constraint_column_usage.constraint_name
,constraint_column_usage.table_name AS table_name_ref
,constraint_column_usage.column_name AS column_name_ref
,cols_ref.ordinal_position AS ordinal_position_ref
FROM information_schema.constraint_column_usage
JOIN information_schema.columns cols_ref ON cols_ref.table_name::TEXT = constraint_column_usage.table_name::TEXT
AND cols_ref.column_name::TEXT = constraint_column_usage.column_name::TEXT
) s2 ON s1.constraint_name::TEXT = s2.constraint_name::TEXT
AND NOT s1.table_name::TEXT = s2.table_name_ref::TEXT;

用法:

 select table_name from vdepend_table where table_name_ref='a'

关于postgresql - 获取将被级联截断的表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35077265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com