Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query multiple columns on a given value in postgresql

Tags:

sql

postgresql

I have a table in my database (postgres) Table #1

----------------------------------------------------    
| name  |  id_a |  id_b | id_c | id_d |  id_e | id_f    
----------------------------------------------------

I am now given a list of ids. Some of these ids belong to id_b, some to id_c and so on till id_f. For these list of ids I need to find the corresponding id_a.

Method #1 Identify which ids belong to id_b, id_c and so on. Then use multiple in clause in my mysql-query to fetch id_a

select id_a from Table #1 t1 where t1.id_b in () or t1.id_c in ().... or t1.id_f in ();

I am looking for an alternative way.

Method #2

Is there some way to query all the columns simultaneously for a given value. Something like

select id_a from Table #1 t1 where t1.id_b,t1.id_c,..t1.id_f in ();
like image 889
raizsh Avatar asked Jan 27 '23 10:01

raizsh


1 Answers

In postgres, you can use the array-overlap, &&, operator:

SELECT id_a
FROM   mytable
WHERE  ARRAY[id_b, id_c, id_d, id_e, id_f] && ARRAY[value1, value2, ...]
like image 67
Mureinik Avatar answered Feb 12 '23 14:02

Mureinik