【问题标题】:Select data for columns that are only in another table为仅在另一个表中的列选择数据
【发布时间】:2020-09-12 00:47:09
【问题描述】:

我有两个表,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';      

我需要从 table2 中选择数据,只选择 table1 中的列。

【问题讨论】:

  • 您需要使用动态 SQL 来执行此操作。

标签: sql postgresql


【解决方案1】:

我目前没有 postrgesql intace,但您需要的是 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 '

【讨论】:

    【解决方案2】:

    如果从移动应用程序写入时出现任何语法错误,您可以加入两个结果集以获取通用数据。

    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'; 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 2017-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多