我有一个带有 IN 子句的准备好的语句
SELECT locationId,
location,
FROM location_type
where city in (?)
and userId = ?
我尝试使用准备好的语句查询执行上述查询
execute ps using 'NY','CA','12345';
但这被视为3个参数,我还在AWS控制台中尝试了上述查询,在param1中传递“NY”,“CA”,在param2中传递“12345”,但它没有返回任何结果。
尝试了其他方法,将两个值作为 JSON 数组,然后转换为带有逗号分隔值的字符串,但这也不会返回任何结果
SELECT locationId,
location,
FROM location_type
where city in (array_join(cast(? as array(varchar)), ', '))
and userId = ?
execute ps using json '["NY","CA"]','12345';
在 athena/presto 中也找不到 IN 子句的任何示例
您可以使用 CTE,而不是使用 IN。
以下是基本 CTE 的示例:
with city_list_cte as (
select *
from (
select '["NY","CA"]' as city_list, '12345' as userid --I believe this is where you would substitute ?
) as lt
cross join unnest(
cast(
json_parse(city_list) as array < varchar >
)
) as t(city)
)
select *
from city_list_cte
它获取城市列表,转换为 json 并使用 UNNEST 为每个值提供一行。
然后您可以将其加入到您的其他表中。 类似于以下内容,但没有示例数据,我无法完全测试:
with city_list_cte as (
select *
from (
select '["NY","CA"]' as city_list, '12345' as userid --I believe this is where you would substitute ?
) as lt
cross join unnest(
cast(
json_parse(city_list) as array < varchar >
)
) as t(city)
)
SELECT locationId,
location,
FROM location_type lt
JOIN city_list_cte cl on cl.city = lt.city and cl.userid = lt.userId
我在哪里有 city_list 和 userid 的硬编码值,您可以替换它?并根据您的具体需求进行调整。
In 子句不采用逗号分隔值作为准备语句中的参数,因此必须创建一个包含值的 CTE 并分成行,然后作为参数 IN 子句传递
SELECT locationId,
location,
FROM location_type
where city in (select * from
(
WITH t AS (
SELECT ? AS data
)
SELECT value
FROM t
CROSS JOIN UNNEST(split(t.data, ',')) as x(value)))
and userId = ?
prepared statement can be
execute ps using json 'NY,CA','12345';
您需要做的就是这个
SELECT locationId,
location,
FROM location_type
where city in ( ?, ? )
and userId = ?
现在您可以分别传递所有三个参数。