如何向 epgsql sql where in 子句提供列表 (Erlang)
How to provide list to epgsql sql where in clause (Erlang)
我找不到为 epgsql:equery 函数提供值列表以在 sql where in 子句中使用的正确语法。我用谷歌搜索并尝试了几种变体,但都失败了。我的一些尝试如下:
L = [1, 2, 3],
epgsql:equery(Conn, "SELECT ::integer[]", [L]), % this works
epgsql:equery(Conn, "SELECT * FROM users WHERE id IN ", [L]), % doesn't work
epgsql:equery(Conn, "SELECT * FROM users WHERE id IN ()", [L]), % doesn't work
epgsql:equery(Conn, "SELECT * FROM users WHERE id IN (::integer[])", [L]), % doesn't work
epgsql:equery(Conn, "SELECT * FROM users WHERE id IN unnest(::integer[])", [L]), % doesn't work
正确的做法是什么?
使用</code>你只传递单个值,因为数据库将绑定变量视为一些原子数据,而不是文本占位符(本质上,绑定变量的值在语句解析完成后使用)。因此,在您的情况下,您将一个列表传递给数据库(我假设它已转换为 PG 数组)。</p>
<p><a href="https://www.postgresql.org/docs/current/functions-comparisons.html#FUNCTIONS-COMPARISONS-IN-SCALAR" rel="nofollow noreferrer">Postgres documentation</a> says, that for <code>IN
it expects a list of scalar expressions, so array is not expanded with this operator. Alternatively, for array comparison it suggests ANY/SOME
和 ALL
表达式(分别用于 OR
语义和 AND
语义),在右侧你应该提供一个数组来签入。
由于 IN
是 expr = value1 OR expr = value2 OR ...
的 shorthand,您需要将查询转换为:
epgsql:equery(Conn, "SELECT * FROM users WHERE id = ANY(::int[])", [L])
我找不到为 epgsql:equery 函数提供值列表以在 sql where in 子句中使用的正确语法。我用谷歌搜索并尝试了几种变体,但都失败了。我的一些尝试如下:
L = [1, 2, 3],
epgsql:equery(Conn, "SELECT ::integer[]", [L]), % this works
epgsql:equery(Conn, "SELECT * FROM users WHERE id IN ", [L]), % doesn't work
epgsql:equery(Conn, "SELECT * FROM users WHERE id IN ()", [L]), % doesn't work
epgsql:equery(Conn, "SELECT * FROM users WHERE id IN (::integer[])", [L]), % doesn't work
epgsql:equery(Conn, "SELECT * FROM users WHERE id IN unnest(::integer[])", [L]), % doesn't work
正确的做法是什么?
使用</code>你只传递单个值,因为数据库将绑定变量视为一些原子数据,而不是文本占位符(本质上,绑定变量的值在语句解析完成后使用)。因此,在您的情况下,您将一个列表传递给数据库(我假设它已转换为 PG 数组)。</p>
<p><a href="https://www.postgresql.org/docs/current/functions-comparisons.html#FUNCTIONS-COMPARISONS-IN-SCALAR" rel="nofollow noreferrer">Postgres documentation</a> says, that for <code>IN
it expects a list of scalar expressions, so array is not expanded with this operator. Alternatively, for array comparison it suggests ANY/SOME
和 ALL
表达式(分别用于 OR
语义和 AND
语义),在右侧你应该提供一个数组来签入。
由于 IN
是 expr = value1 OR expr = value2 OR ...
的 shorthand,您需要将查询转换为:
epgsql:equery(Conn, "SELECT * FROM users WHERE id = ANY(::int[])", [L])