SQL 查询
SELECT type from types where id in (SELECT type_ids from user where id=1)
这里是子查询
SELECT type_ids from user where id=1
返回 bigint[] 类型的值。
我该如何解决?
答案 0 :(得分:0)
如果我理解正确,您可以使用 exists
:
select t.type
from types t
where exists (select 1
from user u
where u.id = 1 and
t.id = any (u.type_ids)
);
或者,更简单地说,join
应该做你想做的事:
select t.type
from types t join
users u
on t.id = any(u.type_ids)
where u.id = 1;
虽然如果 type_ids
有重复项,这可以返回重复项。
答案 1 :(得分:0)
值的列表、数组值和the operations you can use for each之间存在细微差别。
IN
运算符将值与值的列表 进行比较,例如返回多行的子查询。因此,它适用于 SELECT type from types where id in (SELECT type_id from user)
is type_id
是单个 bigint
,但子查询返回了多行。
正如文档所说,id in (a, b, c)
等价于 id=a OR id=b OR id=c
,这就是您收到错误的原因:Postgres 尝试计算 id = (SELECT type_ids from user where id=1)
但不知道如何比较bigint
针对一组 bigint (bigint[]
)。
= ANY
运算符将值与 单个数组值 进行比较,这就是您在此处获得的内容:SELECT type_ids from user where id=1
返回单行,但该行中的值是一个数组(一个 bigint[]
值)。
因此编写查询的一种方法是:
SELECT type from types where id = ANY (SELECT type_ids from user where id=1)