【问题标题】:sql - Dynamically select using two lists for the where clausesql - 使用两个列表动态选择 where 子句
【发布时间】:2018-02-01 11:31:04
【问题描述】:

我有两个可变但长度相等的值列表。

Example:
vals1: a, b, c
vals2: 1, 2, 3

做某事的最佳方法是:

select * from table where (col1=vals1[0] and col2=vals2[0]) or (col1=vals1[1] and col2=vals2[1]) or (col1=vals1[2] and col2=vals2[2])

请记住,列表的长度可以是 1 或更多,并且长度始终相同。如果存在另一个选项(最好以 SQL 查询的形式),我不想循环并构建字符串。任何帮助将不胜感激,谢谢。

【问题讨论】:

  • 使用为您使用的任何数据库编写的字符串拆分器函数。 Google 知道很多。
  • 这是什么数据库? SQL 方言不同。
  • 您使用的是什么 DBMS?
  • 我正在使用 postgres
  • where (col1, col2) in (vals1, vals2)? stackoverflow.com/questions/6672665/…

标签: sql postgresql select where-in


【解决方案1】:

unnest 数组并行

select *
from t
where (col1, col2) in (
    select (a,b)
    from (
        select unnest(array['a','b','c']), unnest(array[1,2,3])
    ) s (a,b)
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2020-10-24
    • 2010-09-13
    • 2014-03-03
    相关资源
    最近更新 更多