简体   繁体   中英

Why is array_remove (POSTGRESQL) not working in this case?

This is not working correctly: SELECT array_remove(array_agg(s1->>'karten'),'8 eich.jpg') from spiele;

The output: ["3 eich.jpg","8 eich.jpg","5 sche.jpg","2 herz.jpg","1 laub.jpg","4 eich.jpg","2 sche.jpg","5 laub.jpg","4 herz.jpg","4 sche.jpg"]

The datatype of s1 is json; s1->>'karten' is an array

If karten refers to a JSON array in the, then s1 ->> 'karten doesn't return each element individually, but a one string representing the array. So array_agg() doesn't really aggregate multiple values - only one. The result is an array with a single element - that happens to look like a JSON array.

You can remove an element from a JSON array if the values is jsonb (the recommended data type to handle JSON in Postgres anyway) using the - operator:

select (s1 -> 'karten')::jsonb - '8 eich.jpg'

will return a jsonb value that is an without the key '8 eich.jpg' .

Unfortunately there is no easy conversion from a JSON array to a native array. Search this site, there are multiple answers for that.

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