【问题标题】:Postgresql conditionally include distinct in queryPostgresql 有条件地在查询中包含 distinct
【发布时间】:2021-07-07 19:44:50
【问题描述】:

Postgresql 有条件地在查询中包含 distinct

有没有办法修改查询,例如:

select distinct col1, col2  
            from our_schema.our_table
            where (id = '1001')

目标是轻松激活/停用独特的关键字。

显然,可以将其移至如下评论:

select col1, col2 -- distinct 
            from our_schema.our_table
            where (id = '1001')

在 Postgresql 中是否有任何简单的方法可以做到这一点?

我在使用 TSQL 语言的 Microsoft SSMS 中看到了“动态 SQL”。 Postgresql 有这样的东西吗?或者更简单的东西?

【问题讨论】:

  • 你想申请什么条件?
  • 另外,您如何/从哪里运行此查询?
  • 条件是使用“distinct”关键字。我使用“dbeaver”数据库工具作为运行环境。

标签: postgresql distinct dynamic-sql database-programming


【解决方案1】:

似乎这只是关于代码管理/构建 SQL 字符串?

DISTINCT 之后插入换行符。 SQL 中空格的唯一意义是separate tokens。除此之外,换行符纯粹是装饰性的 - 除了standard comments starting with -- 以行结尾。

SELECT DISTINCT
       col1, col2 ...

-->

SELECT -- DISTINCT
       col1, col2 ...

甚至:

SELECT
       DISTINCT
       col1, col2 ...

-->

SELECT
--     DISTINCT
       col1, col2 ...

或者使用C-style block comments: /* comment */

SELECT DISTINCT col1, col2 ...

-->

SELECT /*DISTINCT*/ col1, col2 ...

【讨论】:

    猜你喜欢
    • 2013-03-08
    • 2021-02-18
    • 2016-09-13
    • 2020-05-09
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    相关资源
    最近更新 更多