如何从表中获取多个不同的列?

问题描述

我需要从基于 row 的表中获取多个不同的值。 目前我使用两个不同的查询获取不同的值。

select distinct a from table;
select distinct b from table;

有没有办法在单个查询中做到这一点。 我使用 JDBCTemplate 从这两个查询获取数据。单个查询是否会比这 2 个单独查询性能更高。 我正在使用 postgresDB。

我想出了以下单个查询,但我认为这不是高性能

select e1.a,e2.b from table t join (select distinct a,id from table)e1 on e1.id=t.id join (select distinct b,id from table)e2 on e2.id=t.id ;

解决方法

两个单一的查询可能是最好的方式。你也可以这样做:

select distinct 'a' as which,a from table
union all
select distinct 'b',b from table;