【问题标题】:Using List inside a postgres Query在 postgres 查询中使用 List
【发布时间】:2022-04-30 10:37:23
【问题描述】:

我有一个动态列表。

list=['a','b','c','d' ..... ] 所以长度可能会改变

我想在查询中比较这些列表值

select * from student where name in(all the list values);

我想将列表值传递到此查询中

我怎么能做到这一点.. ???请帮忙 谢谢

【问题讨论】:

  • 您是否使用程序语言来生成 SQL 并获取动态列表?哪一个?
  • list 来自哪里?
  • LIST 实际上是一个位置列表...我想根据 LIST 中的值过滤我的选择查询。列表是从前端复选框生成的
  • 你的编程语言是什么?示例代码是什么?
  • 在 JAVA 列表中 loc_list= new ArrayList(); loc_list.add("班加罗尔"); loc_list.add("pune"); .(其动态可以更多) String sql1 = "select * from tbl_meeting where location in (loc_list)";我如何从该 LOC_LIST 中存在的属于该位置的位置获取所有数据

标签: sql postgresql


【解决方案1】:

在 Postgres 中,您可以使用数组。 where 子句中的语法如下:

where name = any (array[1, 2, 3])

where name = any (list_parameter)

【讨论】:

    【解决方案2】:

    您可以编写一个函数,获取一个列表作为参数并返回一个字符串,如“'one', 'two','three'”。

        // need a string like this 'one', 'two'
        private String arrayToSqlInChecker(List<String> loc_list) {
            StringBuilder value = new StringBuilder("");
            for (int i = 0; i < loc_list.size(); i++) {
                value.append("'" + loc_list.get(i) + "'");
                if (i != loc_list.size() - 1) {
                    value.append(",");
                }
            }
            return value.toString();
        }
    

    然后您必须将此字符串附加到您的 PostgreSQL IN 查询中

    "id IN (" + this.arrayToSqlInChecker(loc_list) + ")"
    

    您还可以在函数中处理 null 或空值

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 2021-09-18
      • 2023-03-09
      • 2016-03-18
      • 2016-04-04
      • 1970-01-01
      • 1970-01-01
      • 2021-05-04
      • 2017-06-01
      相关资源
      最近更新 更多