查询以查找并连接 postgres 数据库中的所有表
Query to find and join all tables in a postgres database
我有一个独特的情况,数据库中的所有 table 都将具有相同的列和数据类型,但必须保持为单独的 table。
我想编写一个查询,可以找到所有这些 table 并将它们连接起来,最好使用一列来标识源 table。我需要它 找到 所有 table,而不是指定它们,因为它们会随着时间而改变,重写这个查询可能会很麻烦。
这可能吗?
举例说明:
database: all_data
table: red
columns: date text, value numeric, notes text
table: green
columns: date text, value numeric, notes text
... etc etc
输出将是:
source: date: value: notes:
red 9/24 12 good
red 9/23 1 review
green 9/21 -1 fail
green 9/10 100 excellent
您可以进行动态查询,如下所示:
您必须使用正确的 table_schema 进行过滤。
SELECT
regexp_replace(string_agg('SELECT ''' || table_name || ''' AS source, date, value, notes FROM ' || table_name || ' UNION ALL ', ' '), ' UNION ALL $', ';') AS "query"
FROM information_schema.tables
WHERE table_schema = 'public';
示例输出:
SELECT 'red' AS source, date, value, notes FROM red
UNION ALL
SELECT 'green' AS source, date, value, notes FROM green;
创建一个PL/pgSQL函数(这是一个例子,也许你可以改进它):
CREATE FUNCTION getAllTablesRows() RETURNS TABLE(source text, date text, value numeric, notes text) AS
$$
DECLARE
cursorTables CURSOR FOR SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';
BEGIN
FOR tableName IN cursorTables LOOP
RETURN QUERY EXECUTE format('SELECT %L::text AS source, date, value, notes FROM %I', tableName.table_name, tableName.table_name);
END LOOP;
END;
$$ LANGUAGE 'plpgsql';
调用它:
SELECT * FROM getAllTablesRows();
我有一个独特的情况,数据库中的所有 table 都将具有相同的列和数据类型,但必须保持为单独的 table。
我想编写一个查询,可以找到所有这些 table 并将它们连接起来,最好使用一列来标识源 table。我需要它 找到 所有 table,而不是指定它们,因为它们会随着时间而改变,重写这个查询可能会很麻烦。
这可能吗?
举例说明:
database: all_data
table: red
columns: date text, value numeric, notes text
table: green
columns: date text, value numeric, notes text
... etc etc
输出将是:
source: date: value: notes:
red 9/24 12 good
red 9/23 1 review
green 9/21 -1 fail
green 9/10 100 excellent
您可以进行动态查询,如下所示:
您必须使用正确的 table_schema 进行过滤。
SELECT
regexp_replace(string_agg('SELECT ''' || table_name || ''' AS source, date, value, notes FROM ' || table_name || ' UNION ALL ', ' '), ' UNION ALL $', ';') AS "query"
FROM information_schema.tables
WHERE table_schema = 'public';
示例输出:
SELECT 'red' AS source, date, value, notes FROM red
UNION ALL
SELECT 'green' AS source, date, value, notes FROM green;
创建一个PL/pgSQL函数(这是一个例子,也许你可以改进它):
CREATE FUNCTION getAllTablesRows() RETURNS TABLE(source text, date text, value numeric, notes text) AS
$$
DECLARE
cursorTables CURSOR FOR SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';
BEGIN
FOR tableName IN cursorTables LOOP
RETURN QUERY EXECUTE format('SELECT %L::text AS source, date, value, notes FROM %I', tableName.table_name, tableName.table_name);
END LOOP;
END;
$$ LANGUAGE 'plpgsql';
调用它:
SELECT * FROM getAllTablesRows();