简体   繁体   English

使用 PostgreSQL,我如何使用数组中的项目获取第一列的值?

[英]With PostgreSQL, how would I get the value of column one with an item in an array?

I have an “Inventory" table, with two columns: id (bigint, primary key) and cards (an array).我有一个“Inventory”表,有两列:id(bigint,主键)和cards(数组)。

Suppose my cards column is: ARRAY['IZMI', 'IZCH', 'IZHI']假设我的卡片栏是: ARRAY['IZMI', 'IZCH', 'IZHI']

How would I get the id with just one item in the array, for example 'IZMI' ?我将如何获取数组中只有一项的 id,例如'IZMI'

What would my query be?我的查询是什么?

There are several options:有几种选择:

One is to use the ANY operator:一种是使用ANY运算符:

select *
from inventory
where 'IZMI' = any(cards);

Another is the contains operator @>另一个是包含运算符@>

select *
from inventory
where cards @> array['IZMI'];

The second option is useful if you need to search for multiple matches (all of them must be included in cards . So that would be an AND type comparison.如果您需要搜索多个匹配项(所有匹配项都必须包含在cards中),第二个选项很有用。所以这将是一个AND类型比较。

And finally the overlaps operator &&最后是重叠运算符&&

select *
from inventory
where cards && array['IZMI'];

In contrast to the contains operator the overlaps operator is true if at least one element matches.与包含运算符相反,如果至少一个元素匹配,则重叠运算符为真。 So this is useful if you are want an OR type comparison.因此,如果您想要OR类型比较,这很有用。

More details can be found in the manual更多细节可以在手册中找到

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM