简体   繁体   中英

(Postgresql) How to get all match from array of integer

I want all row matching with group_id pass as input

ex.

Here is my table:-

id |      name      | group_id 
----+----------------+----------
  1 | Alice John     | {1,2,3}
  2 | joshn shukla   | {1,4}
  3 | rishikesh jain | {2,8}

when I execute below query:-

select * from employee where group_id::TEXT ~ '[\{,]2,8[,\}]'

then it returns result become

 id |      name      | group_id 
----+----------------+----------
  3 | rishikesh jain | {2,8}

expected result all match:-

 id |      name      | group_id 
----+----------------+----------
  1 | Alice John     | {1,2,3}
  3 | rishikesh jain | {2,8}

because 2 present in both rows. any solution?

Try:

select * from employee  where  (group_id  && '{2,8}');

Another option would be using regular expressions to get comma-seperated substrings as rows, and then extract the digits only by using

WITH t AS
(
 SELECT e.*, 
        regexp_replace(regexp_split_to_table(group_id, E','),'[^[:digit:]]','','g')::int
             AS num
   FROM employees e
)
SELECT DISTINCT id, group_id
  FROM t
 WHERE num IN (2,8) 

Demo

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