如何参数化此 jsonb 数组包含查询?

How do I parameterize this jsonb array contains query?

我有以下 sql:

WITH
ni AS (SELECT DISTINCT ON(issuercik) issuercik FROM new_insiders
WHERE date_filed > (CURRENT_DATE - INTERVAL '360 day')::date AND ( tickers @> '["MSFT"]'::jsonb ) ORDER BY issuercik, date_filed DESC),
t AS (SELECT cik FROM companies WHERE data->'tickers' @> '["MSFT"]'::jsonb ) 
SELECT ni.issuercik AS first, t.cik AS second FROM ni FULL OUTER JOIN t ON ni.issuercik = t.cik;

这给了我(如预期):

789019 | 789019

现在,我需要参数化查询但无法:

DEALLOCATE stmt;
PREPARE stmt AS WITH
ni AS (SELECT DISTINCT ON(issuercik) issuercik FROM new_insiders
WHERE date_filed > (CURRENT_DATE - INTERVAL '360 day')::date AND ( tickers @> '[""]'::jsonb ) ORDER BY issuercik, date_filed DESC),
t AS (SELECT cik FROM companies WHERE data->'tickers' @> '[""]'::jsonb ) 
SELECT ni.issuercik AS first, t.cik AS second FROM ni FULL OUTER JOIN t ON ni.issuercik = t.cik;

EXECUTE stmt('MSFT');

我得到一个空行,那是因为它实际上是在搜索 ""。我尝试删除双引号然后它抱怨

ERROR:  invalid input syntax for type json
LINE 4: ...DATE - INTERVAL '360 day')::date AND ( tickers @> '[]'::js...
                                                             ^
DETAIL:  Token "$" is invalid.

我不确定如何解决这个问题。

如果您只想检查数组是否包含给定值,可以使用 ? 而不是 @>

看起来像:

DEALLOCATE stmt;

PREPARE stmt AS
WITH
    ni AS (
        SELECT DISTINCT ON(issuercik) issuercik 
        FROM new_insiders
        WHERE 
            date_filed > (CURRENT_DATE - INTERVAL '360 day')::date 
            AND tickers ? 
        ORDER BY issuercik, date_filed DESC
    ),
    t AS (
        SELECT cik 
        FROM companies 
        WHERE data->'tickers' ? 
    ) 
SELECT ni.issuercik AS first, t.cik AS second 
FROM ni 
FULL OUTER JOIN t ON ni.issuercik = t.cik;

EXECUTE stmt('MSFT');