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[]类型的值。
我该如何解决这个问题?
发布于 2021-01-10 13:31:02
如果我理解正确,您可以使用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
有重复项,这可能会返回重复项。
发布于 2021-01-10 13:35:04
值列表、数组值和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
与bigints数组(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)
https://stackoverflow.com/questions/65653749
复制相似问题