【问题标题】:How to get multiple distinct columns from a table?如何从表中获取多个不同的列?
【发布时间】:2021-06-13 23:17:11
【问题描述】:

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

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

有没有办法在单个查询中做到这一点。 我正在使用 JDBCTemplate 从这两个查询中获取数据。单个查询是否会比这两个单独的查询更高效。 我正在使用 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 ;

【问题讨论】:

    标签: mysql sql postgresql jdbc jdbctemplate


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-19
      • 2021-06-21
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多