如何在 postgreSQL 中合并多个表(使用通配符)

How to merge multiple tables in postgreSQL (using wildcard)

一共有163个table,我想一共加两列。并且应该从前面添加列。请告诉我如何在 postgreSQL

上执行此操作

这是一个 table,有两列要添加。

col1 | col2
-----+-----
0    | 0
0    | 0

还有很多 table...

[TableA]
colA1 | colA2
------+-----
a     | a
a     | a

[TableB]
colB1 | colB2
------+-----
b     | b
b     | b

.
.
.

这就是我最终想要的。

[NewTableA]
col1 | col2 | colA1 | colA2
-----+------+-------+-------
0    | 0    | a     | a
0    | 0    | a     | a

[NewTableB]
col1 | col2 | colB1 | colB2
-----+------+-------+-------
0    | 0    | b     | b
0    | 0    | b     | b

.
.
.

并且它应该只应用于以 'M' 开头的 table。我不想合并163次...请帮帮我

正如其他人提到的,there is no mechanism to prepend columns without dropping/recreating tables or individual columns

要将列附加到每个以“m”开头的 table,您可以使用 anonymous plpgsql code block:

DO
$$
DECLARE tbl_ident regclass;
BEGIN
FOR tbl_ident IN
SELECT
  oid::regclass fqn --this will give you schema qualified, properly quoted table name
FROM
   pg_class
WHERE
  'my_schema'::regnamespace::oid = relnamespace --pick schema(s) you care about
  and relkind = 'r' --ordinary tables only. Does not include views (v),materialized views (m),partitioned tables (p) or foreign tables (f)
  and relname ilike 'm%'
LOOP
  -- append the columns you want to the tables
  EXECUTE 'ALTER TABLE ' || tbl_ident || ' ADD COLUMN col1 integer, ADD COLUMN col2 varchar(1337)';
END LOOP;
END$$