【问题标题】:How to search when parameter is given but return all of the rows when it's null or empty?如何在给定参数时进行搜索,但在参数为空或为空时返回所有行?
【发布时间】:2018-01-09 06:18:07
【问题描述】:

我想编写一个查询,当where 条件中的给定参数为空时返回所有行,但当参数不为空时返回符合条件的行,我正在使用postgres 9.6,这就是我到目前为止,但没有骰子...

编辑

让我澄清一下这个问题

我有一个这样的准备好的声明

select * from students where first_name like $1

我想要做的是当 $1 是 null 时忽略 where 并返回所有学生

谢谢

【问题讨论】:

  • 你在这里使用什么编程语言?
  • 我正在使用 Golang
  • 你是如何从 go 调用查询的?在 go 中检查 null,然后使用过滤器或不使用过滤器执行查询。
  • 这是我的第一个想法,但如果可能的话,我想用一个查询来处理它
  • 可以将逻辑封装在服务器端函数中。 stackoverflow.com/questions/17353445/…

标签: sql postgresql prepared-statement


【解决方案1】:

您可以通过以下方式实现:

@FirstName 是传递给查询的参数:

select * from students where first_name like @FirstName or @FirstName is null;

【讨论】:

    【解决方案2】:

    这里是具有明确定义逻辑的准备好的语句示例:

    t=# prepare st(text) as select oid,datname 
    from pg_database 
    where case when $1 is null then true else datname like '%'||$1||'%' end;
    PREPARE
    t=# execute st('post');
      oid  | datname
    -------+----------
     13505 | postgres
    (1 row)
    
    t=# execute st(null);
      oid  |  datname
    -------+-----------
     13505 | postgres
     16384 | t
         1 | template1
     13504 | template0
     16419 | o
     16816 | db
    (6 rows)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 2020-05-12
      相关资源
      最近更新 更多