如何在运算符动态SQL中使用查询

时间:2019-07-31 13:57:23

标签: sql postgresql

在我的前端,我有一个用于标签的过滤器,它向后端发送一个字符串数组,并在数据库中进行搜索。

问题是我有五个不同的列,在某些情况下,查询可以返回true(该列中有值),但也可以返回false(该列中没有值),即,我使用ORAND使查询动态化。

我尝试使用CASE WHEN,但没有成功。

我的查询是这样的:

SELECT
  *
  FROM
table AS cll
WHERE
cll.fill IS NULL

AND
  (
    (
    CASE 
      WHEN cast(cast(integerField as text) = ANY(ARRAY['15', '']) as boolean) = TRUE 
        THEN cast(integerField as text) = ANY(ARRAY['15', '2']) AND 
        ELSE cast(integerField as text) = ANY(ARRAY['15', '2']) OR

      END
    )
  )

//others

但是我有错误:

  

错误:“ END”处或附近的语法错误           ^

有人可以帮助我吗?我不知道为什么。

我需要的查询

SELECT
    *
FROM
    table AS cll
WHERE
    cll.filled_by IS NULL
AND
    cast(integerField as text) = ANY(ARRAY['15', 'existCity']) //TRUE
OR //OR if is false or AND if is true
    city = ANY(ARRAY['15', 'existCity']) //TRUE
OR //OR if is false or AND if is true
    country = ANY(ARRAY['15', 'existCity']) //FALSE

预期结果:

integerField    |      city      |       country
15                  'exitsCity'          'Brazil'

1 个答案:

答案 0 :(得分:0)

未经测试,但您可以尝试

SELECT
    *
FROM
    table AS cll
WHERE
    cll.filled_by IS NULL
    AND (   case
                when    cast(integerField as text) = ANY(ARRAY['15', 'existCity'])
                then    cast(integerField as text) = ANY(ARRAY['15', 'existCity'])
                        and city = ANY(ARRAY['15', 'existCity'])
                        and country = ANY(ARRAY['15', 'existCity'])
                else    cast(integerField as text) = ANY(ARRAY['15', 'existCity'])
                        or city = ANY(ARRAY['15', 'existCity'])
                        or country = ANY(ARRAY['15', 'existCity'])
            end)