PostgreSQL:选择 search_path 中出现表名的第一个模式

问题描述 投票:0回答:1

完成标题中内容的查询将解决我的问题。

我的问题:

我想提取表的列名和数据类型。这是我的查询:

SELECT
    column_name,
    data_type
FROM
    information_schema.columns
WHERE
    table_name = '<table_name>'
ORDER BY ordinal_position;

考虑到该表在整个数据库中仅出现一次,这非常有效。如果它出现在多个模式中,则此查询将返回该名称的所有表的所有列和数据类型。

我知道我只想处理该表在

search_path
中的第一次出现,即其模式首先出现在
search_path
中的表。如何提取该信息,以便我可以在查询中的
table_schema
information_schema.columns
列上设置条件?

postgresql information-schema search-path
1个回答
0
投票

感谢@Bergi,他对查询进行了评论以获取正确的架构名称。

这是解决我在问题中概述的问题的完整查询,使用@Bergi的查询作为子查询:

SELECT
    column_name,
    data_type
FROM
    information_schema.columns
WHERE
    table_name = '<table_name>'
    AND table_schema = (SELECT relnamespace::regnamespace::text FROM pg_class where oid = '<table_name>'::regclass)
ORDER BY ordinal_position;
© www.soinside.com 2019 - 2024. All rights reserved.