简体   繁体   中英

postgreSQL hstore if contains value

Is there a way to check if a value already exists in the hstore in the query itself.

I have to store various values per row ( each row is an "item"). I need to be able to check if the id already exists in database in one of the hstore rows without selecting everything first and doing loops etc in php. hstore seems to be the only data type that offers something like that and also allows you to select the column for that row into an array.

Hstore may not be the best data type to store data like that but there isn't anything else better available.

The whole project uses 9.2 and i cannot change that - json is in 9.3.

The exist() function tests for the existence of a key. To determine whether the key '42' exists anywhere in the hstore . . .

select *
from (select test_id, exist(test_hs, '42') key_exists
      from test) x
where key_exists = true;
test_id  key_exists
--
2        t

The svals() function returns values as a set. You can query the result to determine whether a particular value exists.

select *
from (select test_id, svals(test_hs) vals
      from test) x
where vals = 'Wibble';

hstore Operators and Functions


create table test (
  test_id serial primary key,
  test_hs hstore not null
);

insert into test (test_hs) values (hstore('a', 'b'));
insert into test (test_hs) values (hstore('42', 'Wibble'));

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