WHERE-IN 语句:在数据库上执行 SQL 查询时出错:误用了行值

WHERE-IN statement: error while executing SQL query on database: row value misused

我收到这个错误

Error while executing SQL query on database X: row value misused

对于以下查询模式:

SELECT *
FROM some_table
WHERE (field1, field2) IN (('a', 'b'), ('c', 'd'))

有什么问题的提示吗?

来自Row Value Comparisons

For a row-value IN operator, the left-hand side (hereafter "LHS") can be either a parenthesized list of values or a subquery with multiple columns. But the right-hand side (hereafter "RHS") must be a subquery expression.

在你的例子中 (('a', 'b'), ('c', 'd')) 不是子查询表达式。

您可以做的是创建一个 returns 括号中的行值的 CTE,并使用从该 CTE 中选择的子查询:

WITH cte(field1, field2) AS (VALUES ('a', 'b'), ('c', 'd'))
SELECT *
FROM some_table
WHERE (field1, field2) IN (SELECT field1, field2 FROM cte)

或更简单:

WITH cte(field1, field2) AS (VALUES ('a', 'b'), ('c', 'd'))
SELECT *
FROM some_table
WHERE (field1, field2) IN cte

查看简化版 demo.