我只是为此制定了一个特定于postgresql的选项。它有点像黑客,有自己的优缺点和局限性,但它似乎是有效的,而且不局限于特定的开发语言、平台或PG驱动程序。
当然,诀窍是找到一种方法,将任意长度的值集合作为单个参数传递,并让db将其识别为多个值。我的解决方案是从集合中的值构造一个带分隔符的字符串,将该字符串作为单个参数传递,并使用string_to_array()与PostgreSQL正确使用它所需的强制转换。
因此,如果你想搜索“foo”,“blah”和“abc”,你可以将它们连接成一个字符串,如:'foo,blah,abc'。下面是直接的SQL语句:
select column from table
where search_column = any (string_to_array('foo,blah,abc', ',')::text[]);
显然,您可以将显式强制转换更改为您想要的结果值数组——int、text、uuid等。因为函数接受一个字符串值(或者两个,如果你也想自定义分隔符),你可以在准备好的语句中作为参数传递它:
select column from table
where search_column = any (string_to_array($1, ',')::text[]);
这甚至足够灵活,可以支持like比较:
select column from table
where search_column like any (string_to_array('foo%,blah%,abc%', ',')::text[]);
Again, no question it's a hack, but it works and allows you to still use pre-compiled prepared statements that take *ahem* discrete parameters, with the accompanying security and (maybe) performance benefits. Is it advisable and actually performant? Naturally, it depends, as you've got string parsing and possibly casting going on before your query even runs. If you're expecting to send three, five, a few dozen values, sure, it's probably fine. A few thousand? Yeah, maybe not so much. YMMV, limitations and exclusions apply, no warranty express or implied.
但它确实有效。