6

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 ();
0

3 Answers 3

6

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, ...]
Sign up to request clarification or add additional context in comments.

1 Comment

ouch… I just tried, I had to use WHERE ARRAY[a::text, b::text] && ARRAY['foo', 'bar'] (the casts), and it’s slow because it cannot use the indicēs on the columns
4

Yesss, you can do it like

SELECT columnA
FROM tableA
WHERE (columnA, columnB, columnC)::text IN ('TEST', 'TEST2');

The cast ::text may be required

1 Comment

(columnA, columnB, columnC)::text groups the columns together so your output looks like valueA,valueB,valueC if you want to make this work it needs to be LIKE ('%TEST%') not sure performance vs an alternative solution
1

you can use union

select * from t where id_a in (

select * from 
(select id_b  from t union
select id_c from t union
select id_d from t union
select id_e from t union
select id_f from t
 ) as t1
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.