在单个查询查找多个表中的数据

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

我在PostgreSQL工作,我proble是这样的:我有序列不同的ID 3个表。例如,如果我在表1中插入一行,该ID将是“00001”,如果我在表3中插入一个行的ID将是“00002” ....

所以,我试图创建一个查询,从三个表使用单个查询获取数据。我不知道是否有必要创建一个函数PLPGSQL或只是一个简单的查询,我没有做呢。

我想是这样的:(但在PostgreSQL)

function getData(ID){
  if( ID exists in table 1){
    return select * from table 1
  }
  if( ID exists in table 2){
    return select * from table 1
  }
  if( ID exists in table 3){
    return select * from table 3
  }
}

但当然,这个代码是用另一种语言与错,伪代码。

任何建议?

sql postgresql
1个回答
3
投票

为什么不直接使用union all

select t1.* from table1 t1 where t1.id = 1
union all
select t2.* from table2 t2 where t2.id = 1
union all
select t3.* from table3 t3 where t3.id = 1
© www.soinside.com 2019 - 2024. All rights reserved.