简体   繁体   中英

How can I find out if the values in an array exist in a Postgres table

I am trying to determine if values in a postgres array field correspond to values in another table.

I have a table: cars

id | name | contents
1  | Ford | {1, 3, 5}

and table: contents

id | name | desc
1  | Phone | ....
2  | Keys  | ....

I want to see if the any of the value in contents(field) correspond with any ids in content(table). This is a Postgres database.

从id所在的内容中选择*(从汽车中选择unnest(内容))

You can use the <@ operator (array-contained-by), which is indexable using the intarray extension's GiST opclasses:

SELECT ...
FROM cars
INNER JOIN contents ON (ARRAY[contents.id] @< cars.contents);

or use = ANY :

SELECT ...
FROM cars
INNER JOIN contents ON (contents.id = ANY (cars.contents));

... but this is probably mismodelling; you should probably have a join table between the two tables to model this m:n relationship, not shove it into an array.

See:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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