我有两个表table1和table2,它们具有共同的列。下面给出了获取每个表的列名的查询,
查询以从第一个表中获取列:
select column_name from information_schema.columns
where table_schema = 'schema1'
and table_name = 'table1';
查询以从第二表获得列:
select column_name from information_schema.columns
where table_schema = 'schema2'
and table_name = 'table2';
我需要从表2中选择数据,只有表1中也有列。
目前我没有postrgesql的知识,但是您需要Dynamic SQL。
下面的查询将使您同时出现在表1和表2中的列名。
select string_agg(column_name, ',') FROM (
select column_name from information_schema.columns
where table_schema = 'schema1'
and table_name = 'table1'
intersect
select column_name from information_schema.columns
where table_schema = 'schema2'
and table_name = 'table2'
)
并且您需要构建
EXECUTE 'select ' || select string_agg(column_name, ',') FROM (
select column_name from information_schema.columns
where table_schema = 'schema1'
and table_name = 'table1'
intersect
select column_name from information_schema.columns
where table_schema = 'schema2'
and table_name = 'table2'
) || ' from schema2.table2 '
索里如果有任何语法错误,从移动应用写作,你可以加入这两个结果集来获得共同的数据。
select column_name from information_schema.columns T2
JOIN (select column_name from information_schema.columns where table_schema = 'schema1' and table_name = 'table1') T1
ON T2.COLUMN_NAME = T1.COLUMN_NAME Where T2.table_schema = 'schema2' and T2.table_name = 'table2';