我确信这是一个重复的问题,从某种意义上说答案就在那里,但是我在谷歌上搜索了10分钟后还没有找到答案,所以我呼吁编辑们不要关闭它,因为它可能对其他人很有用。
我使用的是Postgres 9.5。这是我的表格:
Column │ Type │ Modifiers
─────────────────────────┼───────────────────────────┼─────────────────────────────────────────────────────────────────────────
id │ integer │ not null default nextval('mytable_id_seq'::regclass)
pmid │ character varying(200) │
pub_types │ character varying(2000)[] │ not null
我想在pub_types
中找到所有带有"Journal“的行。
我找到了文档,用谷歌搜索了一下,这是我尝试过的:
select * from mytable where ("Journal") IN pub_types;
select * from mytable where "Journal" IN pub_types;
select * from mytable where pub_types=ANY("Journal");
select * from mytable where pub_types IN ("Journal");
select * from mytable where where pub_types contains "Journal";
我扫描了the postgres array docs,但看不到如何运行查询的简单示例,而且StackOverflow问题似乎都是基于更复杂的示例。
发布于 2016-09-22 23:49:16
这应该是可行的:
select * from mytable where 'Journal'=ANY(pub_types);
即语法是<value> = ANY ( <array> )
。另请注意,postresql中的字符串文字是用单引号编写的。
发布于 2018-06-09 03:49:52
尽管这可能不是最有效的方法,但这对我来说很有效:
select * from mytable
where array_to_string(pub_types, ',') like '%Journal%'
但是,使用contains运算符@>
(参见上面Sudharsan Thumatti的答案)可能是一个性能更高的选择,因为它在每个PostgreSQL docs上使用B树比较函数。
根据您的规范化需求,使用FK引用实现一个单独的表可能更好,因为您可能会获得更好的性能和可管理性。
发布于 2019-01-12 07:16:04
我们可以使用数组类型转换为枚举数组的ANY
来代替IN
,例如:
create type example_enum as enum (
'ENUM1', 'ENUM2'
);
create table example_table (
id integer,
enum_field example_enum
);
select
*
from
example_table t
where
t.enum_field = any(array['ENUM1', 'ENUM2']::example_enum[]);
或者我们仍然可以使用'IN‘子句,但首先,我们应该’取消嵌套‘它:
select
*
from
example_table t
where
t.enum_field in (select unnest(array['ENUM1', 'ENUM2']::example_enum[]));
https://stackoverflow.com/questions/39643454
复制相似问题