Postgres:检查数组字段是否包含值?

问题描述:

我肯定这是一个重复的问题,因为答案在某处,但是在谷歌搜索10分钟后我一直找不到答案,所以我呼吁编辑们不要在对其他人可能很有用的基础上将其关闭。

I'm sure this is a duplicate question in the sense that the answer is out there somewhere, but I haven't been able to find the answer after Googling for 10 minutes, so I'd appeal to the editors not to close it on the basis that it might well be useful for other people.

我正在使用Postgres 9.5。这是我的表格:

I'm using Postgres 9.5. This is my table:

        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。

I want to find all the rows with "Journal" in pub_types.

我找到了文档并用谷歌搜索,这就是我尝试过的:

I've found the docs and googled and this is what I've tried:

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";

我已经扫描 postgres数组文档,但看不到如何运行查询的简单示例,而且*问题似乎都基于更复杂的示例。

I've scanned the postgres array docs but can't see a simple example of how to run a query, and * questions all seem to be based around more complicated examples.

这应该有效:

select * from mytable where 'Journal'=ANY(pub_types);

即语法为< value> = ANY(< array>)。还要注意,postresql中的字符串文字是用单引号引起来的。

i.e. the syntax is <value> = ANY ( <array> ). Also notice that string literals in postresql are written with single quotes.